Lists

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 [ ]:
a = ["cat", "dog", "horse"]
In [ ]:
print(a)

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 [ ]:
a[0]

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

In [ ]:
a[2]

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

In [ ]:
a[3]

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

In [ ]:
a[-1]

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

In [ ]:
a[-3]

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

In [ ]:
help(a.append)
In [ ]:
a.append("fish")
In [ ]:
a
In [ ]:
a[3]

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

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

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

In [ ]:
b[3][2]

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

In [ ]:
for x in a:
    print(x)

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

In [ ]:
len(a)

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

In [ ]:
for i in range(0,len(a)):
    print(a[i])

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 [ ]:
s = "Hello World"
In [ ]:
s[-1]

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

In [ ]:
for letter in s:
    print(letter)

Exercises

Exercise 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)

In [ ]:
 

Exercise 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].

In [ ]:
 

Exercise 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.

In [ ]: