Review Structures

Module 2: Data Structures

Before We Begin

This code is designed to test your intuition. Try to understand the code without running it first. I suggest clicking “Edit -> Clear all outputs” in the menu bar at the top of your notebook before you begin. Afterward, you can run the code to check your understanding.

The mid-term will include similar exercises to the ones below (adding multiple-choice answers).


Review of Session 2.1: Lists & Tuples

Exercise

After running this cell, what will be the contents of ls_numbers?

ls_numbers = []

for n in [1, 2, 3]:
  ls_numbers = [n] + ls_numbers
  # Remember you can add a print to see what is happening after every loop!
  # print(f"n = {n} in this loop")
  # print("After this loop the list is:", ls_numbers)

print(ls_numbers)
Exercise

After running this cell, what will be the contents of ls_numbers?

ls_numbers = []

for n in "one, two, three":
  ls_numbers.append(n)

print(ls_numbers)
Exercise

After running this cell, what will be the contents of ls_numbers?

ls_numbers = []

for n in range(2, 11, 2):
  if n == 6:
    continue
  ls_numbers.append(n)

print(ls_numbers)
Exercise

After running this cell, what will be the contents of ls_numbers?

ls_numbers = []

for n in range(10):
  ls_numbers.clear()
  ls_numbers.append(n)

print(ls_numbers)
Exercise

What will be the output of the following cell?

ls_boardgames = ["Monopoly", "Catan", "UNO"]

print(ls_boardgames[1][0])

In case of doubt, think about it one pair of brackets at a time:

# First brackets
output_1 = ls_boardgames[1]
print(output_1)

# Second brackets
output_2 = output_1[0]
print(output_2)

Remember this works the same for tuples!

Exercise

What will be the output of the following cell?

tp_videogames = ("Pokemon", "Candy Crush", "FIFA", "Outer Wilds")

print(tp_videogames[1:3][1])
Exercise

What will be the output of the following cell?

tp_superheroes = ("Batman", "Ironman", "Superman")

print(tp_superheroes[2[1:4]])
Exercise

Which line is going to fail?

tp_colors = ("Blue",)
tp_colors = ("Green",) + tp_colors
tp_colors += ("Red,")
tp_colors.append("Yellow")

print(tp_aliens)
Exercise

Consider the following code. What will be the output?

numbers = [0, 1, 2, 3]
numbers = numbers.append(4)
print(numbers)

The answer is “None”. The append method modifies the list in-place and returns None. So, after this operation, the numbers list is modified to [0, 1, 2, 3, 4], and the result of numbers.append(4) is None.

If you want to print the modified list, you should do it in two steps:

numbers = [0, 1, 2, 3]
numbers.append(4)
print(numbers)
Exercise

After run this code, what will be the value of ls?

ls = ["Lucy", "Jack", "Alberto"]

ls.sort()
ls.insert(2, "Ben")

print(ls)
Exercise

After run this code, what will be the value of ls?

ls = ["Lucy", "Jack", "Alberto"]

ls.insert(2, "Ben")
ls.sort()

print(ls)
Exercise

After run this code, what will be the value of x?

ls = ["Lucy", "Jack", "Alberto"]

ls.insert(2, "Ben")

x = ls.sort()[0]

print(x)

Tuples

Exercise

Consider the following code. What will be the expected output?

tp_numbers = (4, 2, 3)

print(tp_numbers)
Exercise

Consider the following code. What will be the expected output?

tp_numbers = (4, 2, 3)
tp_numbers[0] = 0

print(tp_numbers[0])
Exercise

Consider the following code. What will be the expected output?

tp_numbers = (4, 2, 3)

print(2 * tp_numbers)
Exercise

Consider the following code. What will be the expected output?

ls_names = ["Raul", "Ana", "Oscar"]
tp_names = tuple(ls_names)

print(tp_names[2])
Exercise

Consider the following code. What will be the expected output?

tp_numbers = (5, 2)
tp_names = ("Raul", "Ana", "Oscar")

print(tp_numbers + tp_names)
Exercise

Consider the following code. What will be the expected output?

ls_names = ["Raul", "Ana", "Oscar"]
tp_names = ("Raul", "Ana", "Oscar")

print(ls_names + tp_names)

Review of Session 2.2: Sets

Exercise

After running this cell, what will inside of st_names?

ls_names = ["Alberto", "Carol"]
tp_names = ("Alberto", "Lucia", "Ramon")
st_names = set(ls_names + list(tp_names))

print(st_names)
Exercise

After running this cell, what will be the length of st_movies?

st_comedy = {"Airplane!", "Shrek"}
st_fantasy = {"Harry Potter", "Shrek", "The Lord of the Rings"}
st_movies = st_comedy | st_fantasy  # union

print(len(st_movies))
Exercise

After running this cell, what will be the length of st_movies?

st_comedy = {"Airplane!", "Shrek"}
st_fantasy = {"Harry Potter", "Shrek", "The Lord of the Rings"}
st_movies = st_comedy and st_fantasy  # intersection

print(len(st_movies))

Remember and does not work for sets! Only &.

Exercise

After running this cell, which two structures will have the same length?

msg = "A B C"

ls_evens = [2, 2, 4, 6]

tp_pairs = ((1, 3), (3, 5), (5, 7))

st_squares = {4, 4, 9, 16}

print(len(msg), len(ls_evens), len(tp_pairs), len(st_squares))
Exercise

The following blocks all fail except one. Which one runs fine?

# Option A
ls_numbers = [1, 2, 3]
ls_numbers[0] = "0"

# Option B
ls_numbers = [1, 2, 3]
ls_numbers = ls_numbers + 4

# Option C
tp_numbers = tuple([1, 2, 3])
tp_numbers[0] = 0

# Option D
st_numbers = set([1, 2, 3])
st_numbers[0] = 2

Answer.

  1. Runs fine. A list can contain ANY kind of element, and mix them!

  2. Fails. You cannot sum a list and a number. We can add 4 to the list by enclosing it in brackets: ls_numbers + [4]

  3. Fails. Tuples are not mutable. They do not allow to change their elements! You can access the element tp_numbers[0] but not change it!

  4. Fails. Sets are not ordered. You cannot index them! st_numbers[0] causes an error.

Exercise

Three friends are choosing a weekend plan. Each friend has a list of plans they want to do together. Write a function that takes these three lists and finds the plan that all three friends like.

laura = ["beach", "cinema", "mountain", "museum", "shopping"]
jose = ["gym",  "mountain", "park", "soccer", "shopping"]
ana = ["beach", "cinema", "mountain", "park", "party"]
# This code solves the problem
laura = set(laura)
jose = set(jose)
ana = set(ana)

intersect = laura & jose & ana
print(list(intersect)[0])
# We can encapsulate the previous cell into a function
# This way, we can reuse it for any other group of friends!

def find_common_places(list1, list2, list3):
  set1 = set(list1)
  set2 = set(list2)
  set3 = set(list3)
  common_places = set1.intersection(set2, set3)
  return common_places

common_places = find_common_places(laura, jose, ana)
print(common_places)
Exercise

Based on the previous example, write a function that identifies which places are liked exclusively by each friend. This means the function should print, for each person, the places that only they like and no one else does.

def find_exclusive_places(list1, list2, list3):
  set1 = set(list1)
  set2 = set(list2)
  set3 = set(list3)
  exclusive1 = set1 - set2 - set3
  print(f"The first person likes {exclusive1} exclusively.")
  exclusive2 = set2 - set1 - set3
  print(f"The second person likes {exclusive2} exclusively.")
  exclusive3 = set3 - set1 - set2
  print(f"The third person likes {exclusive3} exclusively.")

find_exclusive_places(laura, jose, ana)
Exercise

Consider the following code. What will be the expected output?

st_names = {"Raul", "Ana", "Oscar"}

print(st_names)
Exercise

Consider the following code. What will be the expected output?

ls_names = ["Raul", "Ana", "Oscar"]
st_names = set(ls_names)

print(st_names[0])
Exercise

Consider the following code. What will be the expected output?

st1 = {"DOG", "CAT", "MOUSE"}
st2 = {"dog", "cat", "mouse"}

print(st1.intersection(st2))
# Lowercase the set
st2 = {"dog", "cat", "mouse"}

# Important: How to initalize a set
st_lower = set()

for element in st2:
  st_lower.add(element.lower())

print(st_lower)
Exercise

Consider the following code. What will be the expected output?

st1 = {1, 2, 3}
st2 = {1.0, 2.5, 3.0}

print(st1.union(st2))
Exercise

Consider the following code. What will be the expected output?

st1 = {1, 2, 3}
st2 = {"1", "2", "3"}

print(st1.difference(st2))
Exercise

Consider the following code. What will be the expected output?

st1 = {1, 1, 2, 2, 3, 3}
st2 = set([5, 4])

print(st1.union(st2))

Review of Session 2.3: Dictionaries

Exercise

What are the keys of dict_fruits?

name = "orange"

dict_fruits = {
    name: 7,
    "pear": 8,
    "apple": 9
}

print(dict_fruits.keys())
Exercise

What will be the output of this cell?

name = "orange"

dict_fruits = {
    name: 7,
    "pear": 8,
    "apple": 9,
    "orange": 10
}

print(dict_fruits[name])
Exercise

What will be the length of dict_fruits?

name = "orange"

dict_fruits = {
    name: 7,
    "pear": 8,
    "apple": 9,
    "orange": 7
}

print(dict_fruits)
Exercise

What will be the length of dict_fruits?

dict_fruits = {
    "pear": 8,
    "apple": 8,
    "orange": 8,
}

print(dict_fruits)
Exercise

What will be the length of dict_fruits?

dict_foods = {
    "fruits": dict_fruits,
    "vegetables": ["carrot", "broccoli"]
}

print(dict_foods)
Exercise

What will be the length of dict_fruits?

dict_fruits = {
    "pear": 8,
    "apple": 8,
    "orange": 8,
}

dict_fruits = {
    "fruits": dict_fruits
}

print(dict_fruits)
Exercise

What will be the contents of dict_scores?

ls_students = ["A", "B", "C"]
ls_scores = [9, 10, 8.5]

dict_scores = {}

for idx in range(len(ls_students)):
  dict_scores[ls_students[idx]] = ls_scores[idx]
  print(ls_students[idx])

print(dict_scores)
Exercise

What will be the length of dc_crops?

num_parsnip = 20

dc_crops = {
    "parsnip": num_parsnip,
    "potato": 5,
    "cauliflower": 10,
    "kale": 5,
}

print(len(dc_crops))
Exercise

What will be the length of dc_person?

dc_person = {
    "name": "Trisha",
    "children": ["Edward", "Alphonse"],
    "age": 26,
}

dc_person["gender"] = "female"

print(len(dc_person))
Exercise

What will be the value of the key area?

 dc_farm = {
    "length": 10,
    "width": 5,
    "missing": "area"
}

dc_farm["area"] = dc_farm["length"] * dc_farm["width"]
del dc_farm["missing"]

print(dc_farm["area"])
Exercise

What will be the output of the following cell?

nested_dict = {
    "mammal": {
        "dog": "woof",
        "cat": "meow",
    },
    "fish": {
        "tuna": "blub",
        "salmon": "blub blub",
    },
}

print(nested_dict["mammal"]["dog"])
Exercise

What will be the output of the following cell?

nested_dict = {
    "mammal": {
        "dog": "woof",
        "cat": "meow",
    },
    "fish": {
        "tuna": "blub",
        "salmon": "blub blub",
    },
}

print(nested_dict["tuna"])

The nested_dict contains only two keys: “mammal” and “fish”. Even if nested_dict includes other dictionaries within it, it does not recognize the keys of those inner dictionaries.

As a general rule, structures only consider their outermost index level and do not account for any substructures within them.

Exercise

What will be the output of the following cell?

nested_dict = {
    "mammal": {
        "dog": "woof",
        "cat": "meow",
    },
    "fish": {
        "tuna": "blub",
        "salmon": "blub blub",
    },
}

print(nested_dict["fish"]["blub"])

Remember, we index dictionaries by their keys. The example above fails because “blub” is a value.

Exercise

What will be the output of the following cell?

ls_dicts = [
    {"name": "Manuel", "country": "Spain"},
    {"name": "Louis", "country": "Canada"}
]

print(ls_dicts[-1])
Exercise

What will be the output of the following cell?

ls_dicts = [
    {"name": "Manuel", "country": "Spain"},
    {"name": "Louis", "country": "Canada"}
]

print(ls_dicts["Manuel"]["country"])

ls_dicts is a list, so you need to access its elements using numerical indices. If you want to access the dictionary containing “Manuel”, you should do ls_dicts[0].

Exercise

What will be the output of the following cell?

ls_dicts = [
    {"name": "Manuel", "country": "Spain"},
    {"name": "Louis", "country": "Canada"}
]

for d in ls_dicts:
  for v in d.values():
    print(v)