Lists

Lesson Progress
0% Complete

Lists are the most versatile data stracture in Python. They are similar to arrays in other languages. A list is a comma separated values between square brackets. Lists may contain items of different types i.e integers, strings or another list.

Example:python">

list1 = ['physics', 'chemistry', 1997, 2000]
list2 = [1, 2, 3, 4, 5 ]
list3 = ["a", "b", "c", "d"]

Like strings, list indices start at 0, and lists can be indexed and sliced.

python">list1[0]:-  physics

list2[2:5]:-  [3, 4, 5] 

Assignment to slices is also possible, and this can even change the size of the list or clear it entirely:

python">>>> letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g']

>>> letters

['a', 'b', 'c', 'd', 'e', 'f', 'g']

>>> # replace some values

>>> letters[2:5] = ['C', 'D', 'E']

>>> letters

['a', 'b', 'C', 'D', 'E', 'f', 'g']

>>> # now remove them

>>> letters[2:5] = []

>>> letters

['a', 'b', 'f', 'g']

>>> # clear the list by replacing all the elements with an empty list

>>> letters[:] = []

>>> letters

[]

Lists also support operations like concatenation:

>>> list2 + [36, 49, 64, 81, 100]

[1, 2, 3, 4, 5 , 36, 49, 64, 81, 100]

 

Updating a List

Unlike strings, which are immutable, lists are a mutable type, i.e. it is possible to change their content: Example

python">>>> cubes = [1, 8, 27, 65, 125]  # something's wrong here

>>> 4 ** 3  # the cube of 4 is 64, not 65!

64

>>> cubes[3] = 64  # replace the wrong value

>>> cubes

[1, 8, 27, 64, 125]

You can also add new items at the end of the list, by using the append()

python">shoppingList = [] # An empty list initialized  by empty square brackets

shoppingList.append("tomatoes")

shoppingList.append("bread")

shoppingList.append("tissue")

shoppingList.append("pens")

print shoppingList

print shoppingList[0]

print shoppingList[2]

Output

python">['tomatoes', 'bread', 'tissue', 'pens']

Tomatoes

tissue

Delete List Elements

To remove an item from a list given its index instead of its value we use the del statement. This differs from the pop() method which returns a value. The del statement can also be used to remove slices from a list or clear the entire list. For example:

python">>>> a = [-1, 1, 66.25, 333, 333, 1234.5]

>>> del a[0]

>>> a

[1, 66.25, 333, 333, 1234.5]

>>> del a[2:4]

>>> a

[1, 66.25, 1234.5]

>>> del a[:]

>>> a

[]

del can also be used to delete entire variables:

python">>> del a

The built-in function len() is used to get the length of a list

python">>>> letters = ['a', 'b', 'c', 'd']

>>> len(letters)

4

To iterate over items in a list we use range() or membership operator (in).

For example to iterate and print all items in the shopping list:

python">shoppingList = ['tomatoes', 'bread', 'tissue', 'pens']

for item in shoppingList:

print item

Output

tomatoes
bread
tissue
pens

Using range to iterate over a list numbers

python">list2 = [1, 2, 3, 4, 5 ]

for i in range(len(list2)):

    print “Number at index”, i, "is", list[i]

Output: Notice how we access the value using indices

Number at index  0 is 1
Number at index  1 is 2
Number at index  2 is 3
Number at index  3 is 4
Number at index  4 is 5

 

Built-in List Functions & Methods

Python includes the following list functions −

cmp(list1, list2)

Compares elements of both lists.

len(list)

Gives the total length of the list.

max(list)

Returns item from the list with max value.

min(list)

Returns item from the list with min value.

list(seq)

Converts a tuple into list.

Python includes following list methods

list.append(obj)

Appends object obj to list

list.count(obj)

Returns count of how many times obj occurs in list

list.extend(seq)

Appends the contents of seq to list

list.index(obj)

Returns the lowest index in list that obj appears

list.insert(index, obj)

Inserts object obj into list at offset index

list.pop(obj=list[-1])

Removes and returns last object or obj from list

list.remove(obj)

Removes object obj from list

list.reverse()

Reverses objects of list in place

list.sort([func])

Sorts objects of list, use compare func if given