In the course "Introduction to Python" we introduced lists
but did not get a chance to look at Python's tuple
or dict
object. These concepts are used in this lesson, indeed we have already seen a tuple
, so we give a quick introduction. We also look at list comprehension so that you will recoginise what it does when you see it.
import numpy as np
Now let's create an array as before a verify its shapeL
np_array = np.zeros((2, 2))
print(np_array.shape)
When we create a numpy
array using zeros
, eye
or similar functions, and then ask the shape of an array the data structure used is a tuple
. This is like a list
, but is immutable, that is it cannot be changed (you may recall that strings are also immutable). We indicate that a structure is a tuple
by using parentheses rather than the square brackets used for lists
. Otherwise a tuple
is much like a list
:
my_list = [0, 1, 2, 3]
my_tuple = (0 ,1, 2, 3)
print(my_list)
print(my_tuple)
print(my_list[2:])
print(my_tuple[2:])
We can check its mutability or lack of by trying to change one of the items in the tuple
:
my_tuple[3]=4
So far we have looped through lists using the following structure:
my_list = ['Drew', 'Jack', 'James', 'Will']
for name in my_list:
print(name)
we have also seen how we can loop over the list
using range
:
for index in range( len(my_list) ):
print(index, my_list[index])
This is a little difficult to read so Python provides the enumerate
function to provide a more compact and readable way of doing this:
for index, value in enumerate(my_list):
print(index, value)
Again try this out for yourself. This is esepcially useful when we have two lists of related data and we want to compare or change values in one based on the other. For dictionaries you can use for key, value in my_dict.items()
to acehive the same.
List comprehensions are a convenient way of constructing simple lists in one line. For instance:
my_list = [x**2 for x in range(10)]
constructs the list
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
using a list comprehension. This is equivalent to the list constructed by the following code:
my_list = []
for x in range(10):
my_list.append(x**2)
We can also add conditions to list comprehensions, for instance
my_list = [x**2 for x in range(10) if (x**2 )<50]
generates a list of $x^2 $ for $x$ in the range 0 to 9, but only keeps the results less than 50. If you are familiar with the way that sets are represented in mathematics, this way of constructing lists may look familiar. The above code is equivalent to:
my_list = []
for x in range(10):
if (x**2) < 50:
my_list.append(x**2)
but is more compact, but can be less readable.