Lists
Overview
Teaching: 10 min
Exercises: 10 minQuestions
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.
- Dealing with a hundred variables called
subject_001
,subject_002
, etc., would be a wildly inefficient classification system - Use a list to store many values together.
- Contained within square brackets
[...]
. - Values separated by commas
,
.
- Contained within square brackets
- Use
len
to find out how many values are in a list.
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.
- Just like strings.
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.
- Use an index expression on the left of assignment to replace a value.
subjects[0] = 'snakes'
print('subjects is now:', subjects)
subjects is now: ['snakes', 'cats', 'hampsters', 'pets', 'fauna']
Appending items to a list lengthens it.
- Use
list_name.append
to add items to the end of a list.
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']
append
is a method of lists.- Like a function, but tied to a particular object.
- Use
object_name.method_name
to call methods.- Deliberately resembles the way we refer to things in a library.
- We will meet other methods of lists as we go along.
- Use
help(list)
for a preview.
- Use
extend
is similar toappend
, but it allows you to combine two lists. For example:
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.
del list_name[index]
removes an item from a list and shortens the list.- Not a function or a method, but a statement in the language.
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.
- Use
[]
on its own to represent a list that doesn’t contain any values.- “The zero of lists.”
- Helpful as a starting point for collecting values.
Lists may contain values of different types.
- A single list may contain numbers, strings, and anything else (even other lists, as we’ve seen!).
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'
- Explain in simple terms what
list('some string')
does.- What does
'-'.join(['x', 'y'])
generate?
Working With the End
What does the following program print?
element = 'helium' print(element[-1])
- How does Python interpret a negative index?
- 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?
- If
values
is a list, what doesdel values[-1]
do?- 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])
- If we write a slice as
low:high:stride
, what doesstride
do?- 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
andnew = 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.