In section 1, we introduced the list
object type. A list is a collection of objects, arranged in a specific order. A comma separates each entry and the whole thing is surrounded by square brackets.
For example:
exampleList = [1,5,3,2]
type(exampleList)
We often use list
objects to hold a sequence of data which we might want to traverse through in our code.
You can retrieve entries in a list
by specifying the index of the entry in the list
. This is done by putting the index in square brackets after the name of the list
.
Counting of indices in python lists starts at zero, so to pick the first entry in a list
, specify index 0.
eg. to specify the first value of the list
, exampleList
, defined above:
exampleList[0]
Pick out the third entry of the list exampleList
# Exercise 5.1.1 a)
What happens if you try to pick an entry that doesn't exist, for example the tenth entry?
# Exercise 5.1.1 b)
You can also use negative numbers as indices, which start backwards from the end of the list. This is useful if you don't know how long your list is, but want to pick, for example, the last entry:
exampleList[-1]
Pick out the last but one entry in the list, exampleList
, using negative indices
# Exercise 5.1.2
We can use list indexing to change the value of a particular entry in a list.
For example, to change the value of the second entry in exampleList from 5 to 32 we do:
exampleList[1] = 32
Now exampleList looks like:
exampleList
Add 37 the fourth entry in exampleList
.
# Exercise 5.2.1 a)
Check that you have done what you expected by looking at exampleList:
# Exercise 5.2.1 b)
We can also select a section (or slice) of the original list using slicing.
To do this we use the construct:
list[start:end]
Where the end
value is the last index value we want + 1 (similarly to the range operator).
Doing this will return a subset of the original list that only contains the elements covered by the index range.
For example, to select the second to the third entries in exampleList:
exampleList[1:3]
If we want, we can assign this list subset to a new list variable:
small_list = exampleList[1:3]
print(small_list)
Pick out the first to third entries (inclusive) from exampleList
# Exercise 5.3.1
To find the length of a list, we can use the function len()
:
len(exampleList)
The len()
function can be used in more than just list, in fact it can be used to calculate the length of any object that contains a sequence of objects.
For example, we can apply len()
to work out the length of a dictionary:
exampleDictionary = {"foo":1, "bar":2, "pi":3.141}
len(exampleDictionary)
What if you want to update your list and add a further entry?
If you want to add a single entry to the list, you can use the append()
function:
exampleList.append(9)
exampleList
The append()
function is built in the list
object. In python this is called a method function.
If you have a whole other list of entries that you want to add the end of your list, you can add the two lists together to make a third list:
exampleList + [5,2,721]
Otherwise if you want to "in-place" extend the existing list, you can use the extend()
method function.
exampleList.extend([5, 2, 721])
exampleList
Other functions can be used to transform lists, some of the most useful ones are:
sorted()
: sorts a list in ascending order:sum()
: sums the values in a listunsortedlist = [9,2,7,4,1,8,12,6,4,1]
sorted(unsortedlist)
sum(unsortedlist)
a) Find average value of the data in the list below:
Important: In python it is possible for you to overwrite a function (e.g. sum
), so make sure not to assign sum
as a variable!
data = [1,4,6,3,9,12,5,4,20,2,6,4,8,1,1,2,5,4,6,7,3]
# Exercise 5.6.1 a)
b) Add a new data point 17
to the list
# Exercise 5.6.1 b)
c) Find the median value of the data
# Exercise 5.6.1 c)
So far we have been working with lists of integers or floating point values.
What if we have a string that we want to convert to a list? eg. a DNA or protein sequence. To convert a string to a list
, we use list()
.
eg:
DNA = 'ACAATGCGATACGTATTTGCG'
DNA = list(DNA)
print(DNA)
Then we can use list
method functions on the DNA list
.
Find the length of the DNA sequence and change the second-last base to a 'T'
# Exercise 5.7.1
for
loops¶To iterate through values in a list, we use a for
loop.
So to print every value of a list of names, we could do:
for name in ['Jack','Elisa','Rahim','Sterling','Lucas','Anya']:
print(name)
Here, the for
loop iterates through the list
and assigns the name
variable to the next list
element at each loop iteration.
We can also set up the list in advance and refer back to the list
name:
names = ['Jack','Elisa','Rahim','Sterling','Lucas','Anya']
for name in names:
print(name)
From the list
of distances given below, obtain a list
of distances squared
# Exercise 5.8.1
dists = [3.1, 8.4, 9.0, 4.2, 3.0]
List comprehension is a handy shortcut when looping over lists:
dist_squared2 = [dist*dist for dist in dists]
print(dist_squared2)
This does the same thing as above (loops over dists
and for each entry dist
adds dist
x dist
at the corresponding index of a new list, dist_squared2
), only in one line instead of three. You can do a similar thing with dictionaries and tuples.
range
function¶When using a for loop it can sometimes be useful to create a list
of consecutive numbers.
To do this, you can use the range
function in combination with list
comprehension, which returns a list
from 0 to one less than the argument given.
eg:
[ i for i in range(12) ]
Below are two lists, the first gives the amount of growth (in cm) of four pieces of grass in the first twelve hours of the day, the second for the same pieces of grass in the last twelve hours of the day. Find the total amount of growth for each piece of grass.
# Exercise 5.9.1
am = [4.3, 7.1, 9.5, 8.5]
pm = [1.2, 3.2, 4.2, 3.9]
As previously alluded to, there is a special type of keyed list
named dictionary
objects in python.
A dictionary is a list of key:value
objects that is indexed by the value of key
.
When defining a dictionary, it has the form:
dict_name = {key1: value1, key2: value2, ...}
Keys can be strings, integers, tuples; values can be strings, integers, tuples, lists, other dictionaries...
key3 = 3
dict_name = {'key1': 1, (2,2): 'value2', key3: [3,3]}
dict_name
Each key and value form a pair. We can use our dictionary to get the 'value' corresponding to a particular key:
print(dict_name['key1'])
print(dict_name[(2,2)])
print(dict_name[3])
print(dict_name[key3])
After first setting up our dictionary, we can then add or change entries:
dict_name['key1'] = 'newvalue'
dict_name['key1']
dict_name['newkey'] = 4
dict_name['newkey']
Whilst we do not cover dictionaries much in this tutorial, it should be noted that they are a very useful object type that can be used to store data in an ordered manner.
In this section we have learned the following:
list
objects start at zero.list
by their index, using listname[index]
.list
by index, using listname[index1:index2]
where index2
is one larger than the index of the last entry you want to select.list
using the len()
function.list
using the append()
method function.+
or the extend()
method function.list
using the sort()
function.list
using the sum()
function.string
to a list
using list()
.list
using for
.range
function to create a list
of consecutive numbers.dictionary
object.