Lists tutorial

Lists are tricky and you’ll need some time to play with them.  We’ll try something a little different this time — you’ll go through a tutorial and take notes as you go.  I encourage you to try the examples listed and extend them: try different parameters, doing things in different orders, etc.  By the end, you need to show me a program that creates a list of all the days of the week, prints them out, removes Saturday and Sunday then prints that out prints that out.  You should then sort the days of the week alphabetically.  Finally, you should reverse that sorting and print the third item in the resulting list.

As you work, it will be helpful for you to draw out lists to visualize their state.  For example, if I were to create a list to hold weather forecast values in Seattle for the next 7 days, I would use the following code:

>>>temps = [54, 51, 47, 48, 53, 54, 46]

It is helpful to then draw the list in the following manner:

Picture 7

Notice that the first value is always stored at index 0.

Once you have shown me that you have completed the tutorial, continue working on tic-tac-toe or the die rolls simulator.

This tutorial was remixed from Rui Peixoto’s Python List Tutorial on Knol.  Thanks!

Basic concepts

Creating and initializing a list:

A list is always declared using square brackets “[]” with the values inside separated by commas “,”.
>>>myList = [1, 2, 3]
Creates a list with the values 1, 2 and 3
>>>myList = []
Creates an empty list.

A list can have values of multiple types: integer and real numbers, strings, lists or other data types or structures.
The following example is a valid list declaration with values of different types:

>>>myMultiTypeList = ['Hello', 3.4 , [1,2,3]]

You can also initialize a list using the Range function:

>>>range(3) #Range of 3 numbers from 0
[0, 1, 2]
>>>range(2, 5) #Range of number from 2 to 5, excluded
[2, 3, 4]
>>>range(-2,2) #Range from -2 to 2, excluded
[-2, -1, 0, 1]
>>>range(2,8,2) #Range from 2 to 8, excluded, with a step of 2
[2, 4, 6]
>>>range(8,5) #Returns an empty list
[]
>>>range(8,5,-1) #Reverse range from 8 to 5, excluded
[8, 7, 6]

Accessing data on a list:

The easiest way to access data on a list is by providing the index number of the list element inside square brackets, similar to accessing members of an array in languages like C or Java:

>>>myList = [10,22,34,46]
>>>myList[0]
10
>>>myList[2]
34

The first index of a list is 0, and the last index of a list with n elements is n-1.

In python you can access the data in a reverse way using negative indexes, the index -1 will always point to the last value on the list:

>>>myList[-1]
46
>>>myList[-4]
10

You can manipulate a list item in the same way you would use any variable of its type.  For example, we can add to an integer list value:

>>>myList[2] = myList[2] + 5
>>>myList[2]
39

In a list with n elements the index -n points always to the first element of a list.
The index i is equivalent to the negative index -n+i.
In the myList example the index 1 is equivalent to the index -4+1 = -3
>>>myList[1]==myList[-3]
True

If you try to access to an index that doesn’t exist we will get an exception:

>>>myList[5]
Traceback (most recent call last):
File “<stdin>”, line 1, in <module>
IndexError: list index out of range

Another way to access data on a list is using the for cycle:

>>> for value in [1,2,3]:
… print value

1
2
3

It can be very useful for manipulation of the whole list.

Slicing a list:

You can access a value by its index and in addition you can also access a sequential subset of values using the slice. The slice is represented by the colon “:” operator with the starting index on the left and the stop index on the rigth. Both values are optional. Omitting the start value will return every value from the beginning of the list to the stop value, omitting the stop value is similar, it will return from the start index to the end of the list, omitting both will return the full list. Note that the stop value will not be included in the subset, similar to the stop value in the range function.

>>>myList = ['it', 'is', 'time', 'to', 'slice']
>>>myList[2:4]
['time', 'to']
>>>myList[2:3]
['time']
>>>myList[3:3]
[]
>>>myList[2:]
['time', 'to', 'slice']
>>>myList[:3]
['it', 'is', 'time']
>>>myList[:]
['it', 'is', 'time', 'to', 'slice']

Manipulating a List

Changing data on the list

The most basic data change on a list is to assign a new value to an element of the list.

>>>myList = range(4)
>>>myList
[0, 1, 2, 3]
>>>myList[1] = 10
>>>myList
[0, 10, 2, 3]

It is possible to change the data using the slice operator too:

>>>myList[1:3]=[6, 6]
>>>myList
[0, 6, 6, 3]

The size of the sliced list doesn’t have to be the same as the new assigned values. The old values will be replaced with the new ones no matter what the size is.

>>>myList=range(6)
>>>myList[2:5]
[2, 3, 4]
>>>myList[2:5]=[0,1]
>>>myList
[0, 1, 0, 1, 5]
>>>myList[2:3]
[0]
>>>myList[2:3]=[9,9,9]
>>>myList
[0, 1, 9, 9, 9, 1, 5]

When using the slice only iterables can be assigned, otherwise an exception will be thrown.

>>>myList[2:3] = 1
Traceback (most recent call last):
File “<stdin>”, line 1, in <module>
TypeError: can only assign an iterable

List methods

Lists have several methods you can call on them.  Methods are like functions but are called on a list using “dot notation.”  Take a look at the examples.  We’ll talk more about what is going on when we study objects.

  • append(x)
    • adds x to the end of the list, x is a value
  • extend(L)
    • appends all values of L in the end of the list. L is a list. Passing a value is an error.
  • remove(x)
    • removes the first element on the list with the value x. If x doesn’t exist an exception is thrown.
  • index(x)
    • return the index of the first element with the value x. If x doesn’t exist an exception is thrown.
  • pop(i)
    • removes and returns the value on the index i. If i is omitted the last value of the list is returned an removed.
  • sort()
    • sorts the list in ascending order.
  • reverse()
    • reverses the order of the elements on the list.

>>> myList=range(6)
>>> myList
[0, 1, 2, 3, 4, 5]
>>> myList.append(6)
>>> myList
[0, 1, 2, 3, 4, 5, 6]
>>> myList.extend([7,8,9])
>>> myList
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> a = myList.pop()
>>> a
9
>>> myList
[0, 1, 2, 3, 4, 5, 6, 7, 8]
>>> myList2 = [88, 33, 99, 88, 44, 11]
>>> myList2.index[88]
0
>>> myList2.index(44)
4
>>> myList2.remove(88)
>>> myList2
[33, 99, 88, 44, 11]
>>>myList2.sort()
>>>myList2
>>> myList2.remove(88)
>>> myList2
[33, 99, 88, 44, 11]
>>> myList2.reverse()
>>> myList2
[99, 88, 44, 33, 11]

Operators

=, assign operator

This operator is user to assign a reference to a list. Note that a variable only points to the list on the memory and never contains it. So the assign operator never creates a copy of a list.

>>>myList = [1,2,3] #assigns the reference to the new list
>>>myList2 = myList #myList and myList2 are referencing the same entity
>>>myList2[0] = 0
>>>myList #yes, it’s myList, not myList2
[0,2,3]

One of the easiest ways to get a copy of the list is using the a slice operation without any values:

>>>myList = [1,2,3]
>>>myList2 = myList[:] #a slice instanciates always a new list
>>>myList2[0] = 0
>>>myList
[1,2,3]
>>>myList2
[0,2,3]

+, add operator

This operator adds to lists to a new one.
>>>[1,2,3]+[4,5,6]
[1,2,3,4,5,6]

+=, the “extend” operator
This operator works like the extend method.
>>>myList = [1,2,3]
>>>myList += [4,5]
>>>myList
[1,2,3,4,5]

*, the “repeat” operator

This operator creates a list that creates a new list repeating a defined number of times the sequence of the operated list:
>>>[1,2,3]*2
[1,2,3,1,2,3]
>>>[1,2]*4
[1,2,1,2,1,2,1,2]
>>>[1]*3
[1,1,1]
>>>[]*5
[]