Introduction to Data and Plotting

Interlude: List like structures in Python

Overview

  • Teaching: 5 min
  • Exercises: 5 min

Questions

  • What did the parentheses (, ) indicate in the shape of arrays?
  • What other types of object can I use in Python?

Objectives

  • Understand the difference between a list and a tuple.
  • Understand the difference between a list and a dict.
  • Enumerate provides a compact way of referencing both index and value when looping through lists.
  • Know that list comprehension is just another way of creating a list.

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.

Tuple

In the previous episode introducing numpy we also used a new data structure the tuple, which we will explore a little further. Let's create a new notebook, and import numpy:

In [1]:
import numpy as np

Now let's create an array as before a verify its shapeL

In [2]:
np_array = np.zeros((2, 2))
print(np_array.shape)
(2, 2)

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:

In [3]:
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:])
[0, 1, 2, 3]
(0, 1, 2, 3)
[2, 3]
(2, 3)

We can check its mutability or lack of by trying to change one of the items in the tuple:

In [4]:
my_tuple[3]=4
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-4-0e979b4d83ca> in <module>
----> 1 my_tuple[3]=4

TypeError: 'tuple' object does not support item assignment

Dictionaries

  • Python dicts are like Python lists, they can store anything!
  • Python dicts are different to Python lists in the way they are indexed. Lists are indexed with whole numbers, whereas dicts are indexed with some key, which can be anything. In many cases the key is a string.
  • An empty dict is created with my_dict = dict() or my_dict = {}.
  • We can explicitly construct a dict with my_dict = {'a' : 1, 'b' : 't', 'c' : False}.
  • We can access a value in a dict by using it's key my_dict['b'].
  • We can also easily add or change values in a dictionary: `my_dict['title'] = 'My personal dictionary'

Try this out for yourself.

List Enumeration

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

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.

Key Points

  • Tuples are likke lists but immutable and declared with (, ).
  • Dictionaries are like lists but use a key to reference items rather than an index.
  • Enumerate provides a compact way of iterating index and value in lists.
  • List comprehension is just a compact way of constructing a list.