Lists
Last updated on 2023-05-08 | Edit this page
Overview
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.
- Scenario: You have set up an Arduino to do temperature measurements in a storage room for rare books.
- Doing calculations with a hundred variables called
temperature_001
,temperature_002
, etc., would be at least as slow as doing them by hand. - 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.
PYTHON
temperatures = [17.3, 17.5, 17.7, 17.5, 17.6]
print('temperatures:', temperatures)
print('length:', len(temperatures))
OUTPUT
temperatures: [17.3, 17.5, 17.7, 17.5, 17.6]
length: 5
Use an item’s index to fetch it from a list.
- Just like strings.
PYTHON
print('zeroth item of temperatures:', temperatures[0])
print('fourth item of temperatures:', temperatures[4])
OUTPUT
zeroth item of temperatures: 17.3
fourth item of temperatures: 17.6
Lists’ values can be replaced by assigning to them.
- Use an index expression on the left of assignment to replace a value.
OUTPUT
temperatures is now: [16.5, 17.5, 17.7, 17.5, 17.6]
Appending items to a list lengthens it.
- Use
list_name.append
to add items to the end of a list.
PYTHON
print('temperatures is initially:', temperatures)
temperatures.append(17.9)
temperatures.append(18.2)
print('temperatures has become:', temperatures)
OUTPUT
temperatures is initially: [16.5, 17.5, 17.7, 17.5, 17.6]
temperatures has become: [16.5, 17.5, 17.7, 17.5, 17.6, 17.9, 18.2]
-
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
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.
PYTHON
primes = [2, 3, 5, 7, 11]
print('primes before removing last item:', primes)
del primes[4]
print('primes after removing last item:', primes)
OUTPUT
primes before removing last item: [2, 3, 5, 7, 11]
primes after removing last item: [2, 3, 5, 7]
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 (which we will see in the next episode).
Lists may contain values of different types.
- A single list may contain numbers, strings, and anything else.
Character strings can be indexed like lists.
- Get single characters from a character string using indexes in square brackets.
PYTHON
element = 'carbon'
print('zeroth character:', element[0])
print('third character:', element[3])
OUTPUT
zeroth character: c
third character: b
Character strings are immutable.
- Cannot change the characters in a string after it has been created.
- Immutable: cannot be changed after creation.
- In contrast, lists are mutable: they can be modified in place.
- Python considers the string to be a single value with parts, not a collection of values.
ERROR
TypeError: 'str' object does not support item assignment
- Lists and character strings are both collections.
Indexing beyond the end of the collection is an error.
- Python reports an
IndexError
if we attempt to access a value that doesn’t exist.- This is a kind of runtime error.
- Cannot be detected as the code is parsed because the index might be calculated based on data.
OUTPUT
IndexError: string index out of range
The list’s length would be equal to high - low
.
- It creates a list of the
some string
s characters as elements. - It creates a string composed of
x
andy
, separated by a hyphen character(-
).
Working With the End
What does the following program print?
- 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.)
OUTPUT
m
- A negative index begins at the final element.
-
-(N)
corresponds to the first index, which is the [0] index. - It removes the final element of the list.
- You could do the following:
print(values[0:-1])
OUTPUT
furn
eniroulf
-
stride
indicates both the number of steps, and from which end: positive starts from first element, negative from the last element. element[1::2]
OUTPUT
lithium
''
There is no 20th index, so the entire string is captured.
There is no element after the -1 index.
Program A:
OUTPUT
letters is ['g', 'o', 'l', 'd'] and result is ['d', 'g', 'l', 'o']
Program B:
OUTPUT
letters is ['d', 'g', 'l', 'o'] and result is None
sorted(letters)
returns a sorted copy of the list, while
letters.sort()
sorted the list in place. Thus, it
was already sorted, and calling a further sort returns
None
.
Program A:
OUTPUT
new is ['D', 'o', 'l', 'd'] and old is ['D', 'o', 'l', 'd']
Program B:
OUTPUT
new is ['D', 'o', 'l', 'd'] and old is ['g', 'o', 'l', 'd']
new = old
is assigning old
to
new
, whereas new = old[:]
is a slice
assignment, which will only return a copy of
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.