Programming with Python

Storing Multiple Values in Lists

Learning Objectives

  • Explain what a for loop does.
  • Correctly write for loops to repeat simple calculations.
  • Trace changes to a loop variable as the loop runs.
  • Trace changes to other variables as they are updated by a for loop.

In the first lesson we used NumPy arrays to manipulate temperature data. NumPy arrays are not built into Python: we had to import the library numpy in order to be able to use them. These data structures are the most useful for scientific computing because the allow us to easily do math on our data. For anyone who’s programmed in Matlab or C before, these are also the most familiar data structure (which is why we introduce them first!).

One of the built-in data structures that you will definitely use extensively in Python is the list. Because they are built in, we don’t need to load a library to use them. A list is exactly what it sounds like – a sequence of things that don’t all have to be the same type. Lists are ordered, so we can access the items through an integer index (like we did with NumPy arrays), and one list can simultaneously contain numbers, strings, other lists, numpy arrays, and even commands to run.

Lists are created by putting values, separated by commas, inside square brackets:

odds = [1, 3, 5, 7]
print 'odds are:', odds
odds are: [1, 3, 5, 7]

Because they are ordered, we can select individual elements from lists by indexing:

print 'first and last:', odds[0], odds[-1]
first and last: 1 7

We can change individual elements in a list by assigning new values to them:

odds[-1] = 9
print 'odds are now:', odds
odds are now: [1, 3, 5, 9]

There are many other ways to change the contents of lists besides assigning new values to individual elements:

odds.append(11)
print 'odds after appending a value:', odds
odds after appending a value: [1, 3, 5, 9, 11]
del odds[0]
print 'odds after removing the first element:', odds
odds after removing the first element: [3, 5, 9, 11]
odds.reverse()
print 'odds after reversing:', odds
odds after reversing: [11, 9, 5, 3]

There is one important difference between lists and strings: we can change the values in a list, but we cannot change the characters in a string.

names = ['Newton', 'Darwing', 'Turing'] # typo in Darwin's name
print 'names is originally:', names
names[1] = 'Darwin' # correct the name
print 'final value of names:', names
names is originally: ['Newton', 'Darwing', 'Turing']
final value of names: ['Newton', 'Darwin', 'Turing']
name = 'Tell'
name[0] = 'B'
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-15-220df48aeb2e> in <module>()
      1 name = 'Tell'
----> 2 name[0] = 'B'

TypeError: 'str' object does not support item assignment

If we make a list, (attempt to) copy it and then modify in place, we can cause all sorts of trouble:

print 'Before:\n', 10 * '-'

odds = [1, 3, 5, 7]
primes = odds

print 'primes:', primes
print 'odds:', odds


print '\nAfter:\n', 10 * '-'

primes += [2]

print 'primes:', primes
print 'odds:', odds

Before:
----------
primes: [1, 3, 5, 7]
odds: [1, 3, 5, 7]

After:
----------
primes: [1, 3, 5, 7, 2]
odds: [1, 3, 5, 7, 2]

The command primes = odds doesn’t create a new copy of the list that the variable name odds is assigned to but instead assigns a second variable name to the same list. Essentially, the two variable names point to the exact same location in memory.

Since lists in Python can be modified in place (lists are mutable objects), changing the value of primes edits the contents of the part of memory that both primes and odds point to, causing the value of both variables to change.

To make a copy of a list that is independent of the original, we use the list() command:

print 'Before:\n', 10 * '-'

odds = [1, 3, 5, 7]
primes = list(odds)

print 'primes:', primes
print 'odds:', odds


print '\nAfter:\n', 10 * '-'

primes += [2]

print 'primes:', primes
print 'odds:', odds
Before:
----------
primes: [1, 3, 5, 7]
odds: [1, 3, 5, 7]

After:
----------
primes: [1, 3, 5, 7, 2]
odds: [1, 3, 5, 7]