Storing Multiple Values in Lists

Learning Objectives {.objectives}

  • Explain what a list is.
  • Create and index lists of simple values.

Just as a for loop is a way to do operations many times, a list is a way to store many values. Unlike NumPy arrays, lists are built into the language (so we don't have to load a library to use them). We create a list by putting values inside square brackets:

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

We select individual elements from lists by indexing them:

In [ ]:
print('first and last:', odds[0], odds[-1])

and if we loop over a list, the loop variable is assigned elements one at a time:

In [ ]:
for number in odds:
    print(number)

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. For example, this works:

In [ ]:
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)

But this does not:

In [ ]:
name = 'Bell'
name[0] = 'b'

Ch-Ch-Ch-Changes

Data that can be changed is called mutable, while data that cannot be changed is called immutable. Like strings, numbers are immutable: there's no way to make the number 0 have the value 1 or vice versa. Lists and arrays, on the other hand, are mutable: both can be modified after they have been created.

Programs that modify data in place can be harder to understand than ones that don't because readers may have to mentally sum up many lines of code in order to figure out what the value of something actually is. On the other hand, programs that modify data in place instead of creating copies that are almost identical to the original every time they want to make a small change are much more efficient. You should consider both aspects when writing code.

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

In [ ]:
odds.append(11)
print('odds after adding a value:', odds)
In [ ]:
del odds[0]
print('odds after removing the first element:', odds)
In [ ]:
odds.reverse()
print('odds after reversing:', odds)