Lists

CS 65: Introduction to Computer Science I

Containers

Some types in Python are used for storing a collection of values. These types are called containers.

List: a container type that stores values in a ordered sequence

In [1]:
doctor_who_actors = ["McGann","Eccleston","Tennant","Smith","Capaldi","Whittaker"]
rainfall_amounts = [0.0, 0.3, 0.71, 0.0, 0.32, 1.1, 0.4]
dates = ["March 14, 2020",2021,"4/1"]
empty_list = []

values in a list are called items or elements, e.g., "Capaldi", 0.3

Syntax: start with [, end with ], separate with ,

Accessing items in a list

You can access individual items in a list using their index, which is their position in the list

indices start at 0

In [2]:
doctor_who_actors = ["McGann","Eccleston","Tennant","Smith","Capaldi","Whittaker"]
print(doctor_who_actors[4]) 
Capaldi
In [3]:
rainfall_amounts = [0.0, 0.3, 0.71, 0.0, 0.32, 1.1, 0.4]
print(rainfall_amounts[0])
0.0

Using index notation, you can treat an item in a list like any other variable

In [5]:
rainfall_amounts = [0.0, 0.3, 0.71, 0.0, 0.32, 1.1, 0.4]
total_weekend_rainfall = rainfall_amounts[5] + rainfall_amounts[6] 
total_weekend_rainfall 
Out[5]:
1.5

You will get an error if you try to access an item using an index that is too big for the list.

In [6]:
doctor_who_actors = ["McGann","Eccleston","Tennant","Smith","Capaldi","Whittaker"]
print(doctor_who_actors[7])
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-6-91949d9bfcd0> in <module>
      1 doctor_who_actors = ["McGann","Eccleston","Tennant","Smith","Capaldi","Whittaker"]
----> 2 print(doctor_who_actors[7])

IndexError: list index out of range

But, if you use a negative index, it will count from the back of the list.

In [7]:
doctor_who_actors = ["McGann","Eccleston","Tennant","Smith","Capaldi","Whittaker"]
print(doctor_who_actors[-1])
Whittaker

Updating items in a list

You can also use list notation to change values in a list

In [8]:
rainfall_amounts = [0.0, 0.3, 0.71, 0.0, 0.32, 1.1, 0.4]
rainfall_amounts[2] = 0.65
print(rainfall_amounts)
[0.0, 0.3, 0.65, 0.0, 0.32, 1.1, 0.4]

Group Exercises:

Fill in the blank:

In [ ]:
rainfall_amounts = [0.0, 0.3, 0.71, 0.0, 0.32, 1.1, 0.4]
day_num = int(input("Enter the number of a day 0-6: "))
print("Day",day_num,"had",         ,"inches of rainfall") #Fill in the blank

Add the line of code that will update the list with the new value.

In [ ]:
rainfall_amounts = [0.0, 0.3, 0.71, 0.0, 0.32, 1.1, 0.4]
day_num = int(input("Enter the number of a day 0-6: "))
new_amt = float(input("Enter an updated rainfall amount for that day: "))
#new line of code here

Functions

There are several useful functions that you can use on lists.

Some of them require you to pass the list as an argument

In [9]:
rainfall_amounts = [0.0, 0.3, 0.71, 0.0, 0.32, 1.1, 0.4]
len(rainfall_amounts) #length of the list
Out[9]:
7
In [10]:
max(rainfall_amounts) #largest value in the list
Out[10]:
1.1

Some of them require to use the dot notation. Whenever you use a function with dot notation, it is technically called a method. The distinction will become more important later, but for now, don't be confused if you see the word method in documentation like here: https://docs.python.org/3/tutorial/datastructures.html

In [11]:
rainfall_amounts.index(0.3) #which index can I find 0.3 at?
Out[11]:
1
In [12]:
rainfall_amounts.count(0.0) #how many times does 0.0 appear in the list?
Out[12]:
2

Group Exercises:

Execute this code and explain what is happening.

In [ ]:
doctor_who_actors = ["McGann","Eccleston","Tennant","Smith","Capaldi","Whittaker"]
print( len(doctor_who_actors) )
print( max(doctor_who_actors) )

rainfall_amounts = [0.0, 0.3, 0.71, 0.0, 0.32, 1.1, 0.4]
print( min(rainfall_amounts) )
print( sum(rainfall_amounts) )

rainfall_amounts.reverse()
print(rainfall_amounts)

rainfall_amounts.sort()
print(rainfall_amounts)

What do the min() and sum() functions do?

What do the reverse() and sort() function do?

Can you apply sum() too the doctor_who_actors list?

Write the line of code that will tell you which index "Tennant" appears at in the doctor_who_actors list.

In [ ]:
 

Testing membership in a list

You can test if a value is in a list using the in operator.

In [16]:
doctor_who_actors = ["McGann","Eccleston","Tennant","Smith","Capaldi","Whittaker"]
print("Cushing" in doctor_who_actors)
False
In [17]:
rainfall_amounts = [0.0, 0.3, 0.71, 0.0, 0.32, 1.1, 0.4]
amt = float(input("Enter a rainfall amount: "))
if amt in rainfall_amounts:
    print("that amount appears in the list")
Enter a rainfall amount: 0.32
that amount appears in the list

Group Exercise

Fill in the blank

In [ ]:
doctor_who_actors = ["McGann","Eccleston","Tennant","Smith","Capaldi","Whittaker"]
actor = input("Enter the name of an actor: ")
if             :   #fill in the blank
    print(actor,"has played Doctor Who.")

Appending items to the end of a list

Add new items to the end of a list using the append() list method.

In [18]:
rainfall_amounts = [0.0, 0.3, 0.71, 0.0, 0.32, 1.1, 0.4]
rainfall_amounts.append(0.1)
print(rainfall_amounts)
[0.0, 0.3, 0.71, 0.0, 0.32, 1.1, 0.4, 0.1]

Inserting new items into the beginning/middle of a list

Add new items to the beginning or middlle of a list using the insert() method.

In [19]:
doctor_who_actors = ["McGann","Eccleston","Tennant","Smith","Capaldi","Whittaker"]
doctor_who_actors.insert(1,"Hurt")
print(doctor_who_actors)
['McGann', 'Hurt', 'Eccleston', 'Tennant', 'Smith', 'Capaldi', 'Whittaker']

Group Exercise:

A programmer wants to write a program that allows new rainfall amounts to appear at the beginning of the list. Here's the code they wrote for it, but they have an error in their code. Explain the problem and fix the code.

In [ ]:
rainfall_amounts = [0.0, 0.3, 0.71, 0.0, 0.32, 1.1, 0.4]
new_val = float(input("Enter a new amount: "))
rainfall_amounts.append(new_val)
print(rainfall_amounts)

Removing items by value

When you know the value of the item you want to delete from the list, use the remove() method.

This will only delete the first instance of the value.

If the item isn't there, it will give an error.

In [7]:
rainfall_amounts = [0.0, 0.3, 0.71, 0.0, 0.32, 1.1, 0.4]
rainfall_amounts.remove(0.32)
print(rainfall_amounts)
[0.0, 0.3, 0.71, 0.0, 1.1, 0.4]

Removing items by index

When you know the position of the item you want to delete, use the pop() method.

In [8]:
rainfall_amounts = [0.0, 0.3, 0.71, 0.0, 0.32, 1.1, 0.4]
rainfall_amounts.pop(5)
print(rainfall_amounts)
[0.0, 0.3, 0.71, 0.0, 0.32, 0.4]

Group Exercise:

A programmer wants to write a program that allows the user to enter a rain amount and then remove that if it is in the list. However, when they test this code, some of the tests cause the program to crash. Explain the problem and write the code that will fix it (Hint: you might need to add an if statement).

In [ ]:
rainfall_amounts = [0.0, 0.3, 0.71, 0.0, 0.32, 1.1, 0.4]
val_to_remove = float(input("Enter a value to remove: "))
rainfall_amounts.remove(val_to_remove)
print(rainfall_amounts)