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" ]
a = ["cat", "dog", "horse"]
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
a[0]
The second item is at index 1, and the third item at index 2.
a[2]
What do you think will happen if we access the item at index 3?
a[3]
You can also access the items in the list from the back. What do you think is at index -1?
a[-1]
What about index -2, -3 or -4?
a[-3]
You can add items onto a list by using the .append
function. You can find this using tab completion and Python help...
help(a.append)
a.append("fish")
a
a[3]
You can put whatever you want into a list, including other lists!
b = [ 42, 15, a, [7,8,9] ]
b[3]
Putting lists inside lists allows for multidimensional lookup, e.g. can you work out why b[3][2]
equals 9
?
b[3][2]
You can loop over the items in a list using a for loop, e.g.
for x in a:
print(x)
You can get the number of items in the list using the len
function.
len(a)
You can use this as an alternative way of looping over the elements of a list
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.
s = "Hello World"
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.
for letter in s:
print(letter)