Skip to main content

6.2) Using Lists


In Python, lists are a type of sequence, much more general than strings. They can be sequences of 'things' or objects of any type.
You define a list like this:

>>> my_list = [1,'two', 3.0]
>>> len(my_list)
3

Just like for strings, you can select a specific element (it's called indexing) or slice a list.

>>> my_list[0]
1
>>> my_list[3] # This will return an IndexError because there’s no element 3.
>>> newlist=my_list[1:3]    # you can slice a list
>>> print newlist
['two',3.0]

Unlike for strings, you can easily modify the elements of a list. Lists are mutable (we’ll come back to this concept later):

>>> my_list[1]=52.4
>>> print my_list
[1, 52.4, 3.0]

You can also delete an element from a list:

>>> del my_list[1]
>>> print my_list
[1, 3.0]