Recap 2

Since the first recap, you’ve learned about lists, dictionaries and loops. Let’s revise those concepts and how to use them in this lesson before continuing on to some new material. Answer the questions as best you can, working through any error messages you receive and remembering to refer back to previous lessons.

Lists

First, here’s a reminder of some useful methods (i.e. functions) that apply to lists:

Method Action
list.count(x) Return the number of times x appears in the list
list.insert(i, x) Insert value x at a given position i
list.pop([i]) Remove and return the value at position i (i is optional)
list.remove(x) Remove the first element from the list whose value is x
list.reverse() Reverse the elements of the list in place
list.sort() Sort the items of the list in place
list.index(x) Find the first occurence of x in the list
list[x:y] Subset the list from index x to y-1

Interacting with Lists

Replace ??? in the following code blocks to make the code work as instructed in the comments. All of the methods that you need are listed above, so this is about testing yourself on your understanding both of how to read the help and how to index elements in a list.

a) The next line creates a list of city names (each element is a string) - run the code and check you understand what it is doing.

b) Replace the ??? so that it prints the position of Manchester in the list

print("The position of Manchester in the list is: " + 
      str(cities.index('Manchester')))
The position of Manchester in the list is: 2

c) Replace the ??? so that it prints Belfast

print(cities[2 + 2])
Belfast

d) Use a negative index to print Belfast

print(cities[-2])
Belfast

e) Force Python to generate a list index out of range error. NB: This error happens you provide an index for which a list element does not exist

try: 
    print(cities[6]) #anything above five would do it
except IndexError:
    print("Doesn't exist.")
Doesn't exist.

f) Think about what the next line creates, then run the code.

g) What would you change ??? to, to return [16.5, 13.4, 14.0]?

print(temperatures[1:4])
[16.5, 13.4, 14.0]

h) What are two different ways of getting [15.2, 14.8] from the temperatures list?

print(temperatures[4:6])
print(temperatures[-3:-1])
[15.2, 14.8]
[14.0, 15.2]

i) Notice that the list of temperatures is the same length as the list of cities, that’s because these are (roughly) average temperatures for each city! Given this, how do you print: “The average temperature in Manchester is 13.4 degrees.” without doing any of the following:

  1. Using a list index directly (i.e. cities[2] and temperatures[2]) or
  2. Hard-coding the name of the city?

To put it another way, neither of these solutions is the answer:

print("The average temperature in Manchester is " + str(temperatures[2]) + " degrees.")
city=2
print("The average temperature in " + cities[city] + " is " + str(temperatures[city]) + " degrees.")

Hint: you need to combine some of the ideas we’ve used above!

city  = "Manchester"
index = cities.index(city)
print("The average temperature in " + cities[index] + " is " + str(temperatures[index]) + " degrees.")
The average temperature in Manchester is 13.4 degrees.

Notice that this could also be written:

city = "Manchester"
print("The average temperature in " + 
      cities[cities.index(city)] + " is " + 
      str(temperatures[cities.index(city)]) + " degrees.")
The average temperature in Manchester is 13.4 degrees.

If it works for you, you can think of this as being like substitution in an equation: you can replace index with cities.index(city) because that’s the value we set index to after all!

Substitution

Many time programmers will break a more complex task down into smaller steps: it’s a great general problem solving approach, but in programming you can then use it to (re)compose more complex code.

Now copy+paste your code and change only one thing in order to print out: “The average temperature in Belfast is 15.2 degrees”

city  = "Belfast"
index = cities.index(city)
print("The average temperature in " + cities[index] + " is " + str(temperatures[index]) + " degrees.")
The average temperature in Belfast is 15.2 degrees.

Manipulating Multiple Lists

We’ll create two lists for the next set of questions:

list1 = [1, 2, 3]
list2 = [4, 5, 6]

j) How do you get Python to print: [1, 2, 3, 4, 5, 6]

print ( list1 + list2 )
[1, 2, 3, 4, 5, 6]

k) How to you get Python to print: [1, 2, 3, [4, 5, 6]]

print(list1+[list2])
list1.append(list2) # Alternatively...
print(list1)
[1, 2, 3, [4, 5, 6]]
[1, 2, 3, [4, 5, 6]]

Re-setting the lists now how would you…

l) Print out: [6, 5, 4, 3, 2, 1] ?

list3 = list1+list2
list3.reverse()
print(list3)
[6, 5, 4, 3, 2, 1]

m) Print out: [3, 2, 1, 6, 5, 4] ?

list1.reverse()
list2.reverse()
print( list1+list2 )
[3, 2, 1, 6, 5, 4]

n) How would you print out [3, 2, 6, 5] with a permanent change to the list (not slicing)? NB: this follows on from the previous question, so note that the order is still ‘reversed’.

list1.remove(1)
list2.remove(4)
print( list1+list2 )
[3, 2, 6, 5]

Dictionaries

Remember that dictionaries (a.k.a. dicts) are like lists in that they are data structures containing multiple elements. A key difference between dictionaries and lists is that while elements in lists are ordered, dicts are unordered. This means that whereas for lists we use integers as indexes to access elements, in dictonaries we use ‘keys’ (which can multiple different types; strings, integers, etc.). Consequently, an important concept for dicts is that of key-value pairs.

Creating an Atlas

Replace ??? in the following code block to make the code work as instructed in the comments. If you need some hints and reminders, revisit the Dictionaries Lesson.

Run the code and check you understand what the data structure that is being created (the data for each city are latitude, longitude and airport code)

a) Add a record to the dictionary for Chennai (data here)

cities['Chennai'] = [13.08, 80.27,'MAA']

b) In one line of code, print out the airport code for Chennai

print("The airport code for Chennai is " + cities["Chennai"][2])
The airport code for Chennai is MAA

c) Check you understand the difference between the following two blocks of code by running them, checking the output and editing them (e.g. try the code again, but replacing Berlin with London)

try:
    print(cities['Berlin'])
except KeyError:
    print("Couldn't find key.")
Couldn't find key.
print(cities.get('Berlin'))
None
Tip

So dict.get() does not generate a KeyError, it returns None (or any other value we want; e.g. cities[get('Berlin','New City')]). Depending on how you expect or want your code to behave either approach is valid. Think of it this way: is a missing key a ‘problem’ that needs to be resolved, or just a situation that you expect to encounter.

d) Adapting the code below, print out the city name and airport code for every city in our Atlas.

for k, v in cities.items():
    # Technically the `str` isn't needed here, but it would be wise to 
    # allow for something other than a string to be returned...
    print("The city of " + str(k) + " has an airport code of " + str(v[2]) )
The city of San Francisco has an airport code of SFO
The city of London has an airport code of LDN
The city of Paris has an airport code of PAR
The city of Beijing has an airport code of BEI
The city of Chennai has an airport code of MAA

Loops

Recall from the previous lessons that loops are a way to iterate (or repeat) chunks of code. The two most common ways to iterate a set of commands are the while loop and the for loop.

Working with Loops

The questions below use for loops. Replace ??? in the following code block to make the code work as instructed in the comments. If you need some hints and reminders, revisit the previous lessons.

a) Print out every city on a separate line using a for loop:

for c in cities.keys():
    print(c)
San Francisco
London
Paris
Beijing
Chennai

b) Print out the name and latitude of every city in the cities dictionary using a for loop

for city, attrs in cities.items():
    print(city + " is at latitude " + str(attrs[0]))
San Francisco is at latitude 37.77
London is at latitude 51.51
Paris is at latitude 48.86
Beijing is at latitude 39.92
Chennai is at latitude 13.08

You could also do this using cities.keys() and then looking it up like this: cities[city][0] but in this case that’s a little less clear.

c) Now print using a loop this new data structure:

citiesB = [
    {'name':     'San Francisco',
     'position': [37.77, -122.43],
     'airport':  'SFO'},
    {'name':     'London',
     'position': [51.51, -0.08],
     'airport':  'LDN'},
    {'name':     'Paris',
     'position': [48.86, 2.29],
     'airport':  'PAR'},
    {'name':     'Beijing',
     'position': [39.92, 116.40],
     'airport':  'BEI'}
]

for city in citiesB:
    print(city['name'] + " is at latitude " + str(city['position'][0]))
San Francisco is at latitude 37.77
London is at latitude 51.51
Paris is at latitude 48.86
Beijing is at latitude 39.92

Nice work. Hopefully these questions have helped you compound your understanding. Onwards!

Credits!

Contributors:

The following individuals have contributed to these teaching materials: - James Millington - Jon Reades - Michele Ferretti - Zahratu Shabrina

License

The content and structure of this teaching project itself is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike 4.0 license, and the contributing source code is licensed under The MIT License.

Acknowledgements:

Supported by the Royal Geographical Society (with the Institute of British Geographers) with a Ray Y Gildea Jr Award.

Potential Dependencies:

This lesson may depend on the following libraries: None