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.

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.

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.

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.

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

Use del to remove items from a list entirely.

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.

Lists may contain values of different types.

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

Character strings can be indexed like lists.

element = 'carbon'
print('zeroth character:', element[0])
print('third character:', element[3])
zeroth character: c
third character: b

Character strings are immutable.

element[0] = 'C'
TypeError: 'str' object does not support item assignment

Indexing beyond the end of the collection is an error.

print('99th element of element is:', element[99])
IndexError: string index out of range

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

Solution

The program prints m.

  1. Python interprets a negative index as starting from the end (as opposed to starting from the beginning). The last element is -1.
  2. The last index that can safely be used with a list of N elements is element -N, which represents the first element.
  3. del values[-1] removes the last element from the list.
  4. values[:-1]

Dictionaries contain key-value pairs

The last kind of new data structure we’ll introduce is the Dictionary.

Here is an example of how we can create a dictionary in Python:

myDict = {"A":"Apple", "B":"Boy", "C":"Cat"}

In the above example:

If you just type the name of the variable myDict, all the key value pairs in the dictionary will be printed.

myDict
{'A': 'Apple', 'C': 'Cat', 'B': 'Boy'}

Access Dictionary Elements

Once a dictionary is created, you can access it using the variable to which it is assigned during creation. For example, in our case, the variable myDict can be used to access the dictionary elements.

Here is how this can be done:

myDict["A"]
myDict["B"]
myDict["C"]
'Apple'
'Boy'
'Cat'

So you can see that using the variable myDict and Key as index, the value of corresponding key can be accessed.

There is one thing that you need to keep in your mind. Only dictionary keys can be used as indexes. This means that myDict[“A”] would produce ‘Apple’ in output but myDict[“Apple”] cannot produce ‘A’ in the output.

myDict["Apple"]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'Apple'

So we see that Python complained about ‘Apple’ being used as index.

Update Dictionary Elements

Just the way dictionary values are accessed using keys, the values can also be modified using the dictionary keys. Here is an example to modify python dictionary element:

myDict["A"] = "Application"
myDict["A"]
myDict
'Application'
{'A': 'Application', 'C': 'Cat', 'B': 'Boy'}

You can see that in the example shown above, the value of key ‘A’ was changed from ‘Apple’ to ‘Application’ easily. This way we can easily conclude that there could not be two keys with same name in a dictionary.

Delete Dictionary Elements

Individual elements can be deleted easily from a dictionary. Here is an example to remove an element from dictionary.

del myDict["A"]
myDict
{'C': 'Cat', 'B': 'Boy'}

So you can see that by using ‘del’ an element can easily be deleted from the dictionary.

If you want to delete complete dictionary ie all the elements in the dictionary then it can be done using the clear() function. Here is an example :

myDict.clear()
myDict
{}

So you see that all the elements were deleted making the dictionary empty.

This naturally leads to the command to set up an empty dictionary:

newDict = {}
newDict
{}

Exercises on slides

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.