Cover page images (keyboard)

Lists

Sue Evans

Hit the space bar for next slide

Learning Outcomes

What's a List

Lists vs. Arrays

You may think that a list in Python is the same as an array in C or other languages. They are similar but there are some significant differences.

  1. Although you may have arrays of any type, arrays are homogeneous, meaning they can only hold data of one type. Python lists are heterogeneous. The type of the data being stored can be different at different indices in the same list.
  2. Arrays are a fixed size, but lists shrink and grow as necessary to hold the exact number of items being stored.

Indexing

Indexing of lists in Python is similar to indexing of arrays.

Indices begin with 0.
For a list of length n, the last index will be n - 1.

Here's how we can picture a list of length 5, showing indices of 0 through 4.



 
       
  0 1 2 3 4

Python allows us to use negative indices into a list, as well as positive ones.

The index -1 can be used to access the last item in the list.
The next to the last item can be accessed by using the index, -2, etc.

Lists in Python

There are several ways to create new lists:

>>> # assign the literal empty list
>>> empty = []
>>> empty
[]

>>> # use the list constructor
>>> empty = list()    
>>> empty
[]

>>> # give a literal assignment of items
>>> items = ["bread", "milk", "cheese", "cider"]
>>> #         0        1       2         3
>>> items
['bread', 'milk', 'cheese', 'cider']

>>> # use the list constructor with a string
>>> letters = list("hello")
>>> letters
['h', 'e', 'l', 'l', 'o']

>>> # use split which returns a list of strings
>>> words = "a bunch of words".split()
>>> words
['a', 'bunch', 'of', 'words']

Operators:

Methods:

Built-in functions that operate on lists:

Examples

List Methods

append(item) - add an item to the end of the list

>>> items
['bread', 'milk', 'cheese', 'lemonade']
>>> items.append('ham')
>>> items
['bread', 'milk', 'cheese', 'lemonade', 'ham']
>>> items.append('ham')
>>> items
['bread', 'milk', 'cheese', 'lemonade', 'ham', 'ham']
>>>

count(item) - count occurences of an item in the list

>>> items
['bread', 'milk', 'cheese', 'lemonade', 'ham', 'ham']
>>> items.count('ham')
2
>>> items.count('cheese')
1
>>>

remove(item) - remove the first occurence of an item in the list

>>> items
['bread', 'milk', 'cheese', 'lemonade', 'ham', 'ham']
>>> items.remove('ham')
>>> items
['bread', 'milk', 'cheese', 'lemonade', 'ham']
>>>

extend(list) - append multiple items to end of the list

>>> items.extend(['lettuce', 'tomatoes'])
>>> items
['bread', 'milk', 'cheese', 'lemonade', 'ham', 'lettuce', 'tomatoes']
>>>

index(item) - locate the index of an item in the list

>>> items
['bread', 'milk', 'cheese', 'lemonade', 'ham', 'lettuce', 'tomatoes']
>>> items.index('milk')
1
>>>

insert(index, item) - insert an item before the one at the index

>>> items
['bread', 'milk', 'cheese', 'lemonade', 'ham', 'lettuce', 'tomatoes']
>>> items.insert(2, 'eggs')
>>> items
['bread', 'milk', 'eggs', 'cheese', 'lemonade', 'ham', 'lettuce', 'tomatoes']
>>>

reverse() - reverse the order of the items in the list

>>> items
['bread', 'milk', 'eggs', 'cheese', 'lemonade', 'ham', 'lettuce', 'tomatoes']
>>> items.reverse()
>>> items
['tomatoes', 'lettuce', 'ham', 'lemonade', 'cheese', 'eggs', 'milk', 'bread']
>>>

sort() - sort the list

>>> items
['tomatoes', 'lettuce', 'ham', 'lemonade', 'cheese', 'eggs', 'milk', 'bread']
>>> items.sort()
>>> items
['bread', 'cheese', 'eggs', 'ham', 'lemonade', 'lettuce', 'milk', 'tomatoes']
>>>

Built-In Functions

len(list) - count number of items in the list

>>> items
['bread', 'cheese', 'eggs', 'ham', 'lemonade', 'lettuce', 'milk', 'tomatoes']
>>> len(items)
8
>>>

del(list[index]) - remove the item at the index from the list

>>> items
['bread', 'cheese', 'eggs', 'ham', 'lemonade', 'lettuce', 'milk', 'tomatoes']
>>> del(items[4])
>>> items
['bread', 'cheese', 'eggs', 'ham', 'lettuce', 'milk', 'tomatoes']
>>>

Using lists

Use a list when order matters.

Iterating over sequences

Example using a List

This example shows:


def main():

    # Begin with an empty list
    gpas = []

    # Builds a list of 20 GPAs
    for i in range(20):
        gpa = input("Enter a student's GPA : ")
        gpas.append(gpa)

    # Initialize the accumulator
    total = 0.0

    # Can use "in" instead of range
    for gpa in gpas:
        # Accumulate into total
        total += gpa

    # Calculate average (total is already a float)
    average = total / len(gpas)

    print "The average GPA of this section is ", average


main()

Here's the output

linuxserver1.cs.umbc.edu[132] python list.py
Enter a student's GPA : 3.0
Enter a student's GPA : 3.5
Enter a student's GPA : 2.0
Enter a student's GPA : 2.5
Enter a student's GPA : 1.5
Enter a student's GPA : 4.0
Enter a student's GPA : 2.7
Enter a student's GPA : 2.8
Enter a student's GPA : 3.2
Enter a student's GPA : 3.4
Enter a student's GPA : 2.2
Enter a student's GPA : 2.4
Enter a student's GPA : 1.9
Enter a student's GPA : 2.1
Enter a student's GPA : 2.8
Enter a student's GPA : 2.7
Enter a student's GPA : 3.3
Enter a student's GPA : 3.8
Enter a student's GPA : 3.4
Enter a student's GPA : 3.0
The average GPA of this section is 2.81
linuxserver1.cs.umbc.edu[133]

The Improved List Example

The user needs to understand what the program is doing, so it's important that you always print a greeting.

An important step in coding is to make sure the data structure you are using (in this case a list), gets populated (in this case with the data being entered by the user).


def main():

    # Tell the user what the program will do - Give a Greeting
    print "This program will find the average GPA for a section of 201"
    print

    # Begin with an empty list
    gpas = []

    # Builds a list of 20 GPAs
    for i in range(20):
        gpa = input("Enter a student's GPA : ")
        gpas.append(gpa)

    # Mandatory Debugging Step - Make sure you really made a list!
    # to be removed later
    for i in range(20):
        print "gpas[", i, "] = ", gpas[i]

    # Initialize the accumulator
    total = 0.0

    # Can use "in" instead of range
    for gpa in gpas:
        # Accumulate into total
        total += gpa

    # Calculate average (total is already a float)
    average = total / len(gpas)

    # Add a blank line to separate the input from the result
    print "\nThe average GPA of this section is ", average


main()
This program will find the average GPA for a section of 201

Enter a student's GPA : 3.0
Enter a student's GPA : 3.5
Enter a student's GPA : 2.0
Enter a student's GPA : 2.5
Enter a student's GPA : 1.5
Enter a student's GPA : 4.0
Enter a student's GPA : 2.7
Enter a student's GPA : 2.8
Enter a student's GPA : 3.2
Enter a student's GPA : 3.4
Enter a student's GPA : 2.2
Enter a student's GPA : 2.4
Enter a student's GPA : 1.9
Enter a student's GPA : 2.1
Enter a student's GPA : 2.8
Enter a student's GPA : 2.7
Enter a student's GPA : 3.3
Enter a student's GPA : 3.8
Enter a student's GPA : 3.4
Enter a student's GPA : 3.0
gpas[ 0 ] =  3.0
gpas[ 1 ] =  3.5
gpas[ 2 ] =  2.0
gpas[ 3 ] =  2.5
gpas[ 4 ] =  1.5
gpas[ 5 ] =  4.0
gpas[ 6 ] =  2.7
gpas[ 7 ] =  2.8
gpas[ 8 ] =  3.2
gpas[ 9 ] =  3.4
gpas[ 10 ] =  2.2
gpas[ 11 ] =  2.4
gpas[ 12 ] =  1.9
gpas[ 13 ] =  2.1
gpas[ 14 ] =  2.8
gpas[ 15 ] =  2.7
gpas[ 16 ] =  3.3
gpas[ 17 ] =  3.8
gpas[ 18 ] =  3.4
gpas[ 19 ] =  3.0

The average GPA of this section is  2.81

Now that we know the data being entered is actually being stored in the list, we can remove the debugging loop that prints the list, producing:

This program will find the average GPA for a section of 201

Enter a student's GPA : 3.0
Enter a student's GPA : 3.5
Enter a student's GPA : 2.0
Enter a student's GPA : 2.5
Enter a student's GPA : 1.5
Enter a student's GPA : 4.0
Enter a student's GPA : 2.7
Enter a student's GPA : 2.8
Enter a student's GPA : 3.2
Enter a student's GPA : 3.4
Enter a student's GPA : 2.2
Enter a student's GPA : 2.4
Enter a student's GPA : 1.9
Enter a student's GPA : 2.1
Enter a student's GPA : 2.8
Enter a student's GPA : 2.7
Enter a student's GPA : 3.3
Enter a student's GPA : 3.8
Enter a student's GPA : 3.4
Enter a student's GPA : 3.0

The average GPA of this section is  2.81

List Exercise

In your groups, write Python code that will: