Functions and Classes in Python

Lists

Overview:

  • Teaching: 10 min
  • Exercises: 5 min

Questions

  • What are lists?
  • How do I access the items in a list?
  • How do I modify or add items to a list?

Objectives

  • Revise how to define, access, modify and append to lists
  • Understand the difference between a list and a string

Lists provide a simple way to hold a collection of values. You create a list using square brackets. For example, here we can create a list that contains the values "cat", "dog" and "horse"

a =[ "cat", "dog", "horse" ]
In [1]:
a = ["cat", "dog", "horse"]
In [2]:
print(a)
['cat', 'dog', 'horse']

You can access the items in the list by placing the index of the item in square brackets. The first item is at index 0

In [3]:
a[0]
Out[3]:
'cat'

The second item is at index 1, and the third item at index 2.

In [4]:
a[2]
Out[4]:
'horse'

What do you think will happen if we access the item at index 3?

In [5]:
a[3]
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-5-f75b6be7d8e3> in <module>
----> 1 a[3]

IndexError: list index out of range

You can also access the items in the list from the back. What do you think is at index -1?

In [6]:
a[-1]
Out[6]:
'horse'

What about index -2, -3 or -4?

In [7]:
a[-3]
Out[7]:
'cat'

You can add items onto a list by using the .append function. You can find this using tab completion and Python help...

In [8]:
help(a.append)
Help on built-in function append:

append(object, /) method of builtins.list instance
    Append object to the end of the list.

In [9]:
a.append("fish")
In [10]:
a
Out[10]:
['cat', 'dog', 'horse', 'fish']
In [11]:
a[3]
Out[11]:
'fish'

You can put whatever you want into a list, including other lists!

In [12]:
b = [ 42, 15, a, [7,8,9] ]
In [13]:
b[3]
Out[13]:
[7, 8, 9]

Putting lists inside lists allows for multidimensional lookup, e.g. can you work out why b[3][2] equals 9?

In [14]:
b[3][2]
Out[14]:
9

You can loop over the items in a list using a for loop, e.g.

In [15]:
for x in a:
    print(x)
cat
dog
horse
fish

You can get the number of items in the list using the len function.

In [16]:
len(a)
Out[16]:
4

You can use this as an alternative way of looping over the elements of a list

In [17]:
for i in range(0,len(a)):
    print(a[i])
cat
dog
horse
fish

A string behaves like a list of letters. For example, if we have the string s = "Hello World", then s[0] is "H" and s[-1] is d.

In [18]:
s = "Hello World"
In [19]:
s[-1]
Out[19]:
'd'

You can loop over every letter in a string in the same way that you can loop over every item in a list.

In [20]:
for letter in s:
    print(letter)
H
e
l
l
o
 
W
o
r
l
d

Lists and strings

While lists and strings are similar there are key differences:

  • Strings only contains characters
  • While lists can be modified: an item changed or new items added, strings cannot. Strings are immutable, though any variable can be reassigned a new value.

1

Create two Python lists called a and b. Put into these lists the values [2, 4, 6, 8], and [10, 20, 30, 40]. Check that a[2] equals 6 and b[-1] equals 40. (note that you will need to use the menu "Insert | Insert Cell Below" to insert more cells below to create space for your code)

Solution

2

Now create a loop that loops over each item in a and b and that calculates and prints out the product a[i] * b[i].

Solution

3

Modify your code to create a list called c. Use the .append function to set c[i] = a[i] * b[i]. Check your code by making sure that c[-1] equals 320.

Solution

Key Points:

  • A list stores many values in a single structure.
  • Use an item’s index to fetch it from a list.
  • Python lists start indexing at 0.
  • Lists’ values can be replaced by assigning to them.
  • Appending items to a list lengthens it.
  • Character strings can be indexed like lists.
  • BUT Character strings are immutable.
  • Indexing beyond the end of the collection is an error.
  • Slices beyond the end of a list are empty.
  • If negative indexing is used, then the should be interpreted as the implied i.e. if you have 10 items in a list then the index -1, is the equivalent of 9.
  • Python lists start indexing at 0.