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.
pressure_001
, pressure_002
, etc.,
would be at least as slow as doing them by hand.[...]
.,
.len
to find out how many values are in a list.pressures = [0.273, 0.275, 0.277, 0.275, 0.276]
print('pressures:', pressures)
print('length:', len(pressures))
pressures: [0.273, 0.275, 0.277, 0.275, 0.276]
length: 5
print('First item of pressures is zeroth index:', pressures[0])
print('Fourth index is fifth item of pressures:', pressures[4])
zeroth item of pressures: 0.273
fourth item of pressures: 0.276
pressures[0] = 0.265
print('pressures is now:', pressures)
pressures is now: [0.265, 0.275, 0.277, 0.275, 0.276]
print('99th element of element is:', element[99])
IndexError: string index out of range
list_name.append
to add items to the end of a list (i.e., beyond currently assigned indices)primes = [2, 3, 5]
print('primes is initially:', primes)
primes.append(7)
primes.append(9)
print('primes has become:', primes)
primes is initially: [2, 3, 5]
primes has become: [2, 3, 5, 7, 9]
append
is a method of lists.
object_name.method_name
to call methods.
help(list)
for a preview.extend
is similar to append
, but it allows you to combine two lists. For example:teen_primes = [11, 13, 17, 19]
middle_aged_primes = [37, 41, 43, 47]
print('primes is currently:', primes)
primes.extend(teen_primes)
print('primes has now become:', primes)
primes.append(middle_aged_primes)
print('primes has finally become:', primes)
primes is currently: [2, 3, 5, 7, 9]
primes has now become: [2, 3, 5, 7, 9, 11, 13, 17, 19]
primes has finally become: [2, 3, 5, 7, 9, 11, 13, 17, 19, [37, 41, 43, 47]]
Note that while extend
maintains the “flat” structure of the list, appending a list to a list makes the result two-dimensional.
del
to remove items from a list entirely.del list_name[index]
removes an item from a list and shortens the list.print('primes before removing last item:', primes)
del primes[4]
print('primes after removing last item:', primes)
primes before removing last item: [2, 3, 5, 7, 9]
primes after removing last item: [2, 3, 5, 7]
goals = [1, 'Create lists.', 2, 'Extract items from lists.', 3, 'Modify lists.']
[]
on its own to represent a list that doesn’t contain any values.
element = 'carbon'
print('zeroth character:', element[0])
print('third character:', element[3])
zeroth character: c
third character: b
element[0] = 'C'
TypeError: 'str' object does not support item assignment
:
character (Called ‘slicing’)To retrieve multiple points in a list, specify the start index and the end index plus one
primes = [2, 3, 5, 7, 9, 11, 13, 17, 19]
print(primes[2:5])
[5, 7, 9]
If you want to get all of the items from the beginning of the list until some index, leave the left side of the colon blank
primes = [2, 3, 5, 7, 9, 11, 13, 17, 19]
print(primes[:5])
[2, 3, 5, 7, 9]
Similarly, leaving the right side blank will return all items until the end of the list
primes = [2, 3, 5, 7, 9, 11, 13, 17, 19]
print(primes[5:])
[11, 13, 17, 19]
Or get really fancy by specifying a ‘stride’ parameter, which allows you to jump items.
primes = [2, 3, 5, 7, 9, 11, 13, 17, 19]
# Only take every other item in the slice
print(primes[1:6:2])
[3, 7, 11]
Fill in the Blanks
Copy the following into a blank notebook cell and fill in the blanks so that the program produces the output shown lower down.
values = ____ values.____(1) values.____(3) values.____(5) print('first time:', values) values = values[____] print('second time:', values)
first time: [1, 3, 5] second time: [3, 5]
How Large is a Slice?
If ‘low’ and ‘high’ are both non-negative integers, how long is the list
values[low:high]
?Solution
values = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] low = 3 high = 7 print(len(values[low:high]))
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])
Sort and Sorted
What do these two programs print? In simple terms, explain the difference between
sorted(letters)
andletters.sort()
.# Program A letters = list('gold') result = sorted(letters) print('letters is', letters, 'and result is', result)
# Program B letters = list('gold') result = letters.sort() print('letters is', letters, 'and result is', result)
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 query 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.