Lists tutorial

posted by: Ms. Martin 2 May 2010 2 Comments

Lists are tricky and you’ll need some time to play with them.  We’ll try something a little different this time — I’ll give you just a little background information and 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 submit a program that creates a list of all the days of the week, prints them out, removes Saturday and Sunday then 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.

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

Basic concepts

Why lists?

Lists are the first data structure that we will study.  A data structure is a way of storing related information in an efficient and organized way.  You can think of a list as a container for lots of different variables stored in a particular order.  For example, you might want a list to keep track of all the students in the school.  For each of those students, you might have a list of their classes.

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.

students = ["Jason",  "Jendy", "Jean"]

You can also initialize a list using the range function.  This should give you a little more insight into how a for loop really works.  Remember that our basic for loop structure is for i in range(number). What’s really going on there is that the part after the in keyword needs to be a list.  The i variable then gets values from the list one at a time.

>>>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:

>>>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 one less than the number of elements in that list.

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]
>>>34
>>>myList[2] = myList[2] + 5
>>>myList[2]
39

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

>>>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.  Notice this means we can extend our usage of the for loop to include lists of various types.  For example, we could do:

>>> for name in ["Jason", "Jendy", "Jean"]:
…………print 2 * name
JasonJason
JendyJendy
JeanJean

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]

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[99]
2
>>> myList2.index(44)
4
>>> myList2.remove(88) #Notice only the first 88 is removed
>>> myList2
[33, 99, 88, 44, 11]
>>>myList2.sort()
>>>myList2
[11, 33, 44, 88, 99]
>>> myList2.remove(88)
>>> myList2
[11, 33, 44, 99]
>>> myList2.reverse()
>>> myList2
[99, 44, 33, 11]

Operators

+, add operator

This operator adds two 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
[]

1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading ... Loading ...

Leave a comment

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>