Recap 2

Second Checkpoint

Since the first recap, you've learned about lists, dictionaries and loops. Let's revise those concepts and how to use them in this notebook 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 notebooks.

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.


In [ ]:
cities = ["Bristol", "London", "Manchester", "Edinburgh", "Belfast", "York"]

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


In [ ]:
print("The position of Manchester in the list is: " + str(cities.???('Manchester')))

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


In [ ]:
print(cities[2 + ???])

d) Use a negative index to print Belfast


In [ ]:
print(cities[???])

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


In [ ]:
print(cities[???])

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


In [ ]:
temperatures = [15.6, 16.5, 13.4, 14.0, 15.2, 14.8]

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


In [ ]:
print(temperatures[???])

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


In [ ]:
print(temperatures[???])
print(temperatures[???])

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

or

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!


In [ ]:
city="Manchester" # Use this to get the solution...

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


In [ ]:

1.2 Manipulating Multiple Lists

We'll create two lists for the next set of questions


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

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


In [ ]:
print( ??? )

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


In [ ]:
???
print( list1 )

Let's re-set the lists (run the next code block)


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

l) How would you print out: [6, 5, 4, 3, 2, 1] ?


In [ ]:
list3 = ???
list3.???
print(list3)

m) How would you print out: [3, 2, 1, 6, 5, 4] ?


In [ ]:
list1.???
list2.???
print( list1+list2 )

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


In [ ]:
list1.???
list2.???
print( list1+list2 )

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 Code Camp Lesson 7.

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)


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

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


In [ ]:
cities???

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


In [ ]:
print(???)

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)


In [ ]:
print(cities['Berlin'])

In [ ]:
print(cities.get('Berlin'))

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


In [ ]:
for k, v in cities.items():
    print(k)

Loops

Recall from the previous notebook 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 notebook.

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


In [ ]:
for ??? in cities.???:
    print(??? + " is at latitude " + str(???))

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


In [ ]:
for c in ???:
    print(???)

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


In [ ]:
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 ??? in citiesB.???:
    print(??? + " is at latitude " + str(???))

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

Credits!

Contributors:

The following individuals have contributed to these teaching materials:

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 notebook may depend on the following libraries: None