Lists¶

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.¶

  • Doing calculations with a hundred variables called pressure_001, pressure_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 ,.
  • Use len to find out how many values are in a list.
In [1]:
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

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

In [2]:
print('zeroth item of pressures:', pressures[0])
print('fourth item of pressures:', pressures[4])
zeroth item of pressures: 0.273
fourth item of pressures: 0.276

Lists' values can be replaced by assigning to them.¶

In [5]:
pressures[0] = 0.265
print('pressures is now:', pressures)
pressures is now: [0.265, 0.275, 0.277, 0.275, 0.276]

Appending items to a list lengthens it.¶

  • Use list_name.append to add items to the end of a list.
In [6]:
primes = [2, 3, 5]
print('primes is initially:', primes)
primes.append(7)
print('primes has become:', primes)
primes is initially: [2, 3, 5]
primes has become: [2, 3, 5, 7]
  • 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.
  • extend is similar to append, but it allows you to combine two lists
In [7]:
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]
primes has now become: [2, 3, 5, 7, 11, 13, 17, 19]
primes has finally become: [2, 3, 5, 7, 11, 13, 17, 19, [37, 41, 43, 47]]

Use del to remove items from a list entirely.¶

  • We use del list_name[index] to remove an element from a list (in the example, 9 is not a prime number) and thus shorten it.
  • del is not a function or a method, but a statement in the language.
In [8]:
primes = [2, 3, 5, 7, 9]
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]

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.
In [9]:
goals = [1, 'Create lists.', 2, 'Extract items from lists.', 3, 'Modify lists.']

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.
In [10]:
print('99th element of element is:', element[99])
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In[10], line 1
----> 1 print('99th element of element is:', element[99])

NameError: name 'element' is not defined

Exercise¶

  1. Fill in the blanks so that the program below produces the output shown.
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]
  1. If values is a list that has 30 elements, how many elements does the list values[2:27] have?
  1. Given this:
print('string to list:', list('tin'))
print('list to string:', ''.join(['g', 'o', 'l', 'd']))
string to list: ['t', 'i', 'n']
list to string: gold
  1. What does list('some string') do?
  2. What does '-'.join(['x', 'y', 'z']) generate?
  1. 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?
  1. What do these two programs print? In simple terms, explain the difference between sorted(letters) and letters.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)

Takeaway¶

  • 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.

Continue¶

  1. Lists
  2. Loops
  3. Functions