Skip to content

Workshop: Collections (Optional, Self-Study)

View workshop code on GitHub Get the Video Course

From the lesson

Workshop problems for Section 05 Concepts. Build each yourself first, then expand the solution to check.

Four optional workshop problems, one per concept step; the same ideas as the lesson, in a car scenario. The numbers line up with the steps (Workshop-01 goes with Step-01).

Self-study (not live-coded): the stubs say WHAT to do; you write the code, then check python-workshop/solutions.

Step-01: Lists

Concepts: lists (count, append, insert, extend, remove, pop, sort, reverse, copy, clear, nested lists).

Write a program that, for the cars "Audi", "BMW", "Kia":

  • Task-1: print how many cars there are.
  • Task-2: add "Ford" to the end and print the list.
  • Task-3: insert "Tesla" at index 1 and print the list.
  • Task-4: extend the list with ["Honda", "Mazda"] and print the list.
  • Task-5: remove "BMW" and print the list.
  • Task-6: pop the last car and print what was removed.
  • Task-7: sort the list, then reverse it, and print the list.
  • Task-8: make a copy, clear the original, then print the original and the copy.
  • Task-9: from the nested list [["Audi", 2020], ["Kia", 2022]], print the second car's year.
Expected output
3
['Audi', 'BMW', 'Kia', 'Ford']
['Audi', 'Tesla', 'BMW', 'Kia', 'Ford']
['Audi', 'Tesla', 'BMW', 'Kia', 'Ford', 'Honda', 'Mazda']
['Audi', 'Tesla', 'Kia', 'Ford', 'Honda', 'Mazda']
Mazda
['Tesla', 'Kia', 'Honda', 'Ford', 'Audi']
[]
['Tesla', 'Kia', 'Honda', 'Ford', 'Audi']
2022

Warning

.append(), .insert(), .extend(), .remove(), .sort(), .reverse(), and .clear() all change the list in place and return None. Call each on its own line, never cars = cars.sort(). .copy() returns a NEW list.

Task-1 hint

len(cars) counts how many items are in the list.

Task-2 hint

.append("Ford") adds one item to the END (in place, returns None).

Task-3 hint

.insert(1, "Tesla") drops it in at index 1 and shifts the rest right.

Task-4 hint

.extend(["Honda", "Mazda"]) adds EVERY item from the other list (not the list itself, the way .append would).

Task-5 hint

.remove("BMW") deletes the first item that matches that value.

Task-6 hint

.pop() removes the LAST item AND returns it, so print what it returns.

Task-7 hint

.sort() then .reverse() each change the list in place and return None - call them on their own lines.

Task-8 hint

.copy() returns a NEW list; then .clear() empties the ORIGINAL, so the copy still has the items.

Task-9 hint

Index twice - [1][1] reaches the second inner list, then its second value (Kia year 2022).

Show the solution
s05_workshop01_sol_lists.py
cars = ["Audi", "BMW", "Kia"]
# Task-1: print how many cars there are
print(len(cars))

# Task-2: add Ford to the end and print the list
cars.append("Ford")
print(cars)

# Task-3: insert Tesla at index 1 and print the list
cars.insert(1, "Tesla")
print(cars)

# Task-4: extend the list with two cars and print the list
cars.extend(["Honda", "Mazda"])
print(cars)

# Task-5: remove BMW and print the list
cars.remove("BMW")
print(cars)

# Task-6: pop the last car and print what was removed
print(cars.pop())

# Task-7: sort the list, then reverse it, and print the list
cars.sort()
cars.reverse()
print(cars)

# Task-8: copy, clear the original, print original and copy
backup = cars.copy()
cars.clear()
print(cars)
print(backup)

# Task-9: from the nested list, print the second car's year
car_years = [["Audi", 2020], ["Kia", 2022]]
print(car_years[1][1])

View the full solution file on GitHub

Pages for this step: Concept | Practice | Workshop

Python Files for this step: Concept | Practice | Practice Solutions | Workshop | Workshop Solutions

Step-02: Tuples

Concepts: tuples (index, len, unpack, count, index, in, swap, new tuple, list inside a tuple).

Write a program that, for the car record car = ("Mazda", 2020, "red") (brand, year, color):

  • Task-1: print the brand (first item), the color (last item, negative index), and how many fields there are.
  • Task-2: unpack into brand, year, color and print Mazda 2020 red.
  • Task-3: for the service ratings (4, 5, 4, 4, 3), print how many 4s appear, the position of the 3, and whether a 5 is in there.
  • Task-4: the pair (2020, "Mazda") was typed as (year, brand) by mistake, so unpack it, swap in one line, build the corrected tuple new_car, and print new_car and the original pair.
  • Task-5: a car keeps a list of owners, history = ("Mazda", ["Sam"]): add "Tom" to the owners list and print history, then clear it, add "Amy", and print history again.
Expected output
Mazda
red
3
Mazda 2020 red
3
4
True
('Mazda', 2020)
(2020, 'Mazda')
('Mazda', ['Sam', 'Tom'])
('Mazda', ['Amy'])
Task-1 hint

car[0] is the first item, car[-1] the last (negative index), and len(car) counts the fields.

Task-2 hint

brand, year, color = car gives each field its own name - one per item, in order.

Task-3 hint

.count(4) counts the 4s, .index(3) gives the position of the first 3, and 5 in ratings gives True or False.

Task-4 hint

Unpack a, b = pair, swap in one line a, b = b, a, then build a NEW tuple new_car = (a, b) (a tuple cannot change, so you make a new one); the original pair is unchanged.

Task-5 hint

The tuple is fixed, but history[1] is a LIST, so .append() and .clear() work on it in place - the tuple slot itself never changes.

Show the solution
s05_workshop02_sol_tuples.py
car = ("Mazda", 2020, "red")
# Task-1: print the brand, the color, and the field count
print(car[0])
print(car[-1])
print(len(car))
# Task-2: unpack into brand, year, color and print them
brand, year, color = car
print(brand, year, color)

# Task-3: count the 4s, find the position of the 3, check a 5 is in there
ratings = (4, 5, 4, 4, 3)
print(ratings.count(4))
print(ratings.index(3))
print(5 in ratings)

# Task-4: unpack the swapped pair, swap in one line, build and print the corrected tuple
pair = (2020, "Mazda")
a, b = pair
a, b = b, a
new_car = (a, b)
print(new_car)
print(pair)

# Task-5: change the inner owners list: add, print, clear, add, print again
history = ("Mazda", ["Sam"])
history[1].append("Tom")
print(history)
history[1].clear()
history[1].append("Amy")
print(history)

View the full solution file on GitHub

Pages for this step: Concept | Practice | Workshop

Python Files for this step: Concept | Practice | Practice Solutions | Workshop | Workshop Solutions

Step-03: Dictionaries

Concepts: dictionaries (look up by key, add a key, .get() default, in / not in, len, .update(), .keys() / .items(), del / .pop(), a list value, a nested dict, list of dicts).

Write a program that, for a car dictionary with "brand" set to "Mazda" and "year" set to 2020:

  • Task-1: print the brand.
  • Task-2: add a "color" of "red", then print the whole car dictionary.
  • Task-3: print the owner, falling back to "unknown" when there is no "owner" key.
  • Task-4: print whether "brand" is a key in the car, and whether "owner" is not a key.
  • Task-5: print how many fields the car has now.
  • Task-6: use .update() to set "year" to 2021 and add "price" of 15000 in one call; print the car's keys, then its (key, value) pairs.
  • Task-7: remove "price" with del, then remove "color" with .pop() keeping its value; print the car, then the removed color.
  • Task-8: for a car that keeps a list of services ["oil", "tires"], print the first service, append "brakes", and print the services.
  • Task-9: for a car with a nested owner {"name": "Sam", "city": "Delhi"}, print the owner's city.
  • Task-10: for a garage list holding {"brand": "Mazda", "year": 2021} and {"brand": "Kia", "year": 2022}, print the first car's brand, then the second car's year.
Expected output
Mazda
{'brand': 'Mazda', 'year': 2020, 'color': 'red'}
unknown
True
True
3
['brand', 'year', 'color', 'price']
[('brand', 'Mazda'), ('year', 2021), ('color', 'red'), ('price', 15000)]
{'brand': 'Mazda', 'year': 2021}
red
oil
['oil', 'tires', 'brakes']
Delhi
Mazda
2022
Task-1 hint

car["brand"] looks up a value by its key.

Task-2 hint

Assign to a NEW key to add it: car["color"] = "red", then print(car).

Task-3 hint

car.get("owner", "unknown") returns the default for a missing key instead of a KeyError.

Task-4 hint

in / not in test the KEYS: "brand" in car, "owner" not in car.

Task-5 hint

len(car) counts the key-value pairs.

Task-6 hint

car.update({...}) sets several pairs at once; list(car.keys()) and list(car.items()) turn the views into lists.

Task-7 hint

del car["price"] just discards it; car.pop("color") removes it AND returns the value.

Task-8 hint

A value can be a list: car["services"][0] reads it and car["services"].append(...) grows it.

Task-9 hint

A value can be a nested dict: chain the keys, car["owner"]["city"].

Task-10 hint

A list of dicts is a table: garage[0]["brand"], garage[1]["year"].

Show the solution
s05_workshop03_sol_dictionaries.py
# Task-1: print the brand
car = {"brand": "Mazda", "year": 2020}
print(car["brand"])

# Task-2: add a "color" of "red", then print the whole car dictionary
car["color"] = "red"
print(car)

# Task-3: print the owner, falling back to "unknown" when there is no "owner" key
print(car.get("owner", "unknown"))

# Task-4: print whether "brand" is a key, and whether "owner" is not a key
print("brand" in car)
print("owner" not in car)

# Task-5: print how many fields the car has now
print(len(car))

# Task-6: .update() to set "year" and add "price", then print the keys and the (key, value) pairs
car.update({"year": 2021, "price": 15000})
print(list(car.keys()))
print(list(car.items()))

# Task-7: remove "price" with del, remove "color" with .pop() keeping its value
del car["price"]
removed_color = car.pop("color")
print(car)
print(removed_color)

# Task-8: a value that is a list of services, so read the first, append one, print the list
car = {"brand": "Mazda", "services": ["oil", "tires"]}
print(car["services"][0])
car["services"].append("brakes")
print(car["services"])

# Task-9: a value that is a nested owner dict, so read the city with a chained lookup
car = {"brand": "Mazda", "owner": {"name": "Sam", "city": "Delhi"}}
print(car["owner"]["city"])

# Task-10: a garage list of car dicts, so read the first car's brand and the second car's year
garage = [{"brand": "Mazda", "year": 2021}, {"brand": "Kia", "year": 2022}]
print(garage[0]["brand"])
print(garage[1]["year"])

View the full solution file on GitHub

Pages for this step: Concept | Practice | Workshop

Python Files for this step: Concept | Practice | Practice Solutions | Workshop | Workshop Solutions

Step-04: Sets

Concepts: sets (unique, len, sorted(), empty set() vs {}, set(list) dedup, in / not in, .add(), .update(), .discard(), union |, intersection &, difference -, symmetric difference ^). A set has no order, so every set is printed via sorted().

Problem-1: Unique Brands

Write a program that, for the brand list ["Audi", "BMW", "Audi", "Kia", "BMW"]:

  • Task-1: build a set from the list and print how many UNIQUE brands there are.
  • Task-2: print the unique brands in sorted order.
  • Task-3: print the type of set() to show an empty set is set(), not {} (which is a dict).
Expected output
3
['Audi', 'BMW', 'Kia']
<class 'set'>
Need a hint?

set(brands) drops duplicates, len() counts the uniques, and sorted() prints them; an empty set is set(), not {} (which is a dict).

Show the solution
s05_workshop04_sol_sets.py
brands = ["Audi", "BMW", "Audi", "Kia", "BMW"]
# Problem-1 Task-1: build a set and print the unique count
unique = set(brands)
print(len(unique))
# Problem-1 Task-2: print the unique brands sorted
print(sorted(unique))
# Problem-1 Task-3: print the type of set() to show an empty set
print(type(set()))

View the full solution file on GitHub

Problem-2: Service Tags

Write a program that, for the tag set {"oil", "tires"}:

  • Task-1: add "brakes" with .add(), bulk-add ["filter", "oil"] with .update(), discard "tires" and discard "paint" (not present), then print the sorted tags.
  • Task-2: print whether "oil" is in the tags, and whether "tires" is not in the tags.
Expected output
['brakes', 'filter', 'oil']
True
True
Need a hint?

.add() adds one tag, .update([...]) adds several, and .discard() removes safely; in / not in check membership.

Show the solution
s05_workshop04_sol_sets.py
tags = {"oil", "tires"}
# Problem-2 Task-1: add one tag, then bulk-add more
tags.add("brakes")
tags.update(["filter", "oil"])
# Problem-2 Task-2: discard two tags, print the sorted tags
tags.discard("tires")
tags.discard("paint")
print(sorted(tags))
# Problem-2 Task-3: membership checks with in and not in
print("oil" in tags)
print("tires" not in tags)

View the full solution file on GitHub

Problem-3: Feature Sets

Write a program that, for petrol = {"ac", "abs", "airbag"} and diesel = {"abs", "airbag", "sunroof"}:

  • Task-1: print the sorted union (features in either car).
  • Task-2: print the sorted intersection (in both).
  • Task-3: print the sorted difference (only in petrol).
  • Task-4: print the sorted symmetric difference (in exactly one).
Expected output
['abs', 'ac', 'airbag', 'sunroof']
['abs', 'airbag']
['ac']
['ac', 'sunroof']
Need a hint?

| union, & intersection, - difference, ^ symmetric difference; each returns a new set, so sorted() it to print.

Show the solution
s05_workshop04_sol_sets.py
petrol = {"ac", "abs", "airbag"}
diesel = {"abs", "airbag", "sunroof"}
# Problem-3 Task-1: print the sorted union
print(sorted(petrol | diesel))
# Problem-3 Task-2: print the sorted intersection
print(sorted(petrol & diesel))
# Problem-3 Task-3: print the sorted difference (only in petrol)
print(sorted(petrol - diesel))
# Problem-3 Task-4: print the sorted symmetric difference
print(sorted(petrol ^ diesel))

View the full solution file on GitHub

Pages for this step: Concept | Practice | Workshop

Python Files for this step: Concept | Practice | Practice Solutions | Workshop | Workshop Solutions

Finished this section?

Check your work against the solutions above, then head back to the Section 05 lesson, or try the Section 05 practice for more reps.

Prefer to learn by watching?

The full video course teaches every concept on screen and builds the projects with you, step by step.

Get the Video Course

Workshop: Operators Booleans and Conditionals Next: Workshop: Loops and Comprehensions

🎉 New Course
Python for Absolute Beginners
$15.99 $84.99 81% OFF
Get the Video Course