Lists

Overview

Teaching: 10 min
Exercises: 10 min
Questions
  • How can I store multiple values?

Objectives
  • Explain why programs need collections of values.

  • Write programs that create flat lists, index them, slice them, and modify them through assignment and method calls.

A list stores many values in a single structure.

subjects = ['dogs', 'cats', 'hampsters', 'pets', 'fauna']
print('subjects:', subjects)
print('length:', len(subjects))
subjects: ['dogs', 'cats', 'hampsters', 'pets', 'fauna']
length: 5

Use an item’s index to fetch it from a list.

print('zeroth item of subjects:', subjects[0])
print('fourth item of subjects:', subjects[4])
zeroth item of subjects: dogs
fourth item of subjects: fauna

Lists’ values can be replaced by assigning to them.

subjects[0] = 'snakes'
print('subjects is now:', subjects)
subjects is now: ['snakes', 'cats', 'hampsters', 'pets', 'fauna']

Appending items to a list lengthens it.

cities = ['Vancouver', 'Ontario', 'Montreal']
print('cities is initially:', cities)
cities.append('Saskatoon')
cities.append('Halifax')
print('cities has become:', cities)
cities is initially: ['Vancouver', 'Ontario', 'Montreal']
cities has become: ['Vancouver', 'Ontario', 'Montreal', 'Saskatoon', 'Halifax']
australian_cities = ['Sydney', 'Brisbane', 'Darwin', 'Adelaide', 'Hobart']
french_cities = ['Paris', 'Marseille', 'Strasbourg', 'Nice']
print('cities is currently:', cities)
cities.extend(australian_cities)
print('cities has now become:', cities)
cities.append(french_cities)
print('cities has finally become:', cities)
cities is currently: ['Vancouver', 'Ontario', 'Montreal', 'Saskatoon', 'Halifax']
cities has now become: ['Vancouver', 'Ontario', 'Montreal', 'Saskatoon', 'Halifax', 'Sydney', 'Brisbane', 'Darwin', 'Adelaide', 'Hobart']
cities has finally become: ['Vancouver', 'Ontario', 'Montreal', 'Saskatoon', 'Halifax', 'Sydney', 'Brisbane', 'Darwin', 'Adelaide', 'Hobart', ['Paris', 'Marseille', 'Strasbourg', 'Nice']]

Note that while extend maintains the “flat” structure of the list, appending a list to a list makes the result two-dimensional.

Use del to remove items from a list entirely.

print('cities before removing the fifth item:', cities)
del cities[4]
print('cities after removing the fifth item:', cities)
cities before removing last item: ['Vancouver', 'Ontario', 'Montreal', 'Saskatoon', 'Halifax', 'Sydney', 'Brisbane', 'Darwin', 'Adelaide', 'Hobart', ['Paris', 'Marseille', 'Strasbourg', 'Nice']]
cities after removing last item: ['Vancouver', 'Ontario', 'Montreal', 'Saskatoon', 'Sydney', 'Brisbane', 'Darwin', 'Adelaide', 'Hobart', ['Paris', 'Marseille', 'Strasbourg', 'Nice']]

The empty list contains no values.

Lists may contain values of different types.

goals = [1, 'Create lists.', 2, 'Extract items from lists.', 3, 'Modify lists.']

From Strings to Lists and Back

Given this:

print('string to list:', list('tin'))
print('list to string:', ''.join(['g', 'o', 'l', 'd']))
['t', 'i', 'n']
'gold'
  1. Explain in simple terms what list('some string') does.
  2. What does '-'.join(['x', 'y']) generate?

Working With the End

What does the following program print?

element = 'helium'
print(element[-1])
  1. How does Python interpret a negative index?
  2. If a list or string has N elements, what is the most negative index that can safely be used with it, and what location does that index represent?
  3. If values is a list, what does del values[-1] do?
  4. How can you display all elements but the last one without changing values? (Hint: you will need to combine slicing and negative indexing.)

Stepping Through a List

What does the following program print?

element = 'fluorine'
print(element[::2])
print(element[::-1])
  1. If we write a slice as low:high:stride, what does stride do?
  2. What expression would select all of the even-numbered items from a collection?

Slice Bounds

What does the following program print?

element = 'lithium'
print(element[0:20])
print(element[-1:3])

Copying (or Not)

What do these two programs print? In simple terms, explain the difference between new = old and new = old[:].

# Program A
old = list('gold')
new = old      # simple assignment
new[0] = 'D'
print('new is', new, 'and old is', old)
# Program B
old = list('gold')
new = old[:]   # assigning a slice
new[0] = 'D'
print('new is', new, 'and old is', old)

Key Points

  • A list stores many values in a single structure.

  • Use an item’s index to fetch it from a list.

  • Lists’ values can be replaced by assigning to them.

  • Appending items to a list lengthens it.

  • Use del to remove items from a list entirely.

  • The empty list contains no values.

  • Lists may contain values of different types.

  • Character strings can be indexed like lists.

  • Character strings are immutable.

  • Indexing beyond the end of the collection is an error.