Skip to content

Practice: Collections

View practice code on GitHub Get the Video Course

From the lesson

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

Four practice problems, one per concept step; the numbers line up (Practice-01 goes with Step-01). Build each one yourself in python-practice, then compare with python-practice/solutions. Do this before starting the next section.

Write the code yourself; the stubs only describe the task. Some problems end with a short input() "Write a Program" exercise.

These problems build one connected story: you are setting up the catalog for an online store (products, prices, categories). Each step adds another piece of that catalog.

Step-01: Lists

Concepts: lists (append, insert, extend, pop, clear, sort, reverse, indexing, slicing, in / not in, index / count, copy, nested lists, split(), join(), input()).

Problem-1: Catalog Prices.

Write a program that, starting from the product prices 40, 95, 25 with 60 added in:

  • Task-1: print the prices sorted from lowest to highest.
  • Task-2: print the highest price.
Expected output
[25, 40, 60, 95]
95

Warning

.sort() and .append() change the list in place and return None. Call catalog_prices.sort() on its own line, then print catalog_prices. Do NOT write catalog_prices = catalog_prices.sort(), or catalog_prices becomes None.

Need a hint?

.append() and .sort() change the list in place and return None; call them as statements, then read the highest price as the last item after sorting, [-1].

Show the solution
s05_practice01_sol_lists.py
catalog_prices = [40, 95, 25]
catalog_prices.append(60)
# Problem-1 Task-1: print prices sorted low to high
catalog_prices.sort()
print(catalog_prices)
# Problem-1 Task-2: print the highest price
print(catalog_prices[-1])

View the full solution file on GitHub

Problem-2: Split and Join.

Write a program that:

  • Task-1: split the product code "TEC-2024-15" on - into a list and print the list.
  • Task-2: join the label words "wireless", "gaming", "mouse" with a single space into one string and print it.
Expected output
['TEC', '2024', '15']
wireless gaming mouse
Need a hint?

.split("-") turns product_code into a list of parts; " ".join(label_words) does the reverse, gluing a list back into one string.

Show the solution
s05_practice01_sol_lists.py
# Problem-2 Task-1: split the product code on "-"
product_code = "TEC-2024-15"
print(product_code.split("-"))
# Problem-2 Task-2: join the label words with a space
label_words = ["wireless", "gaming", "mouse"]
print(" ".join(label_words))

View the full solution file on GitHub

Problem-3 (Write a Program): Catalog Items.

Write a program that asks for catalog items separated by commas (no spaces), splits the text into a list, prints the list, and then prints count: followed by how many items there are.

Example run
Items separated by commas (no spaces): mouse,keyboard,monitor
['mouse', 'keyboard', 'monitor']
count: 3
Need a hint?

input() always returns a string; .split(",") breaks it into a list and len(catalog_items) counts the parts.

Show the solution
s05_practice01_sol_lists.py
# Problem-3: read items, split into a list, print list and count
entered = input("Items separated by commas (no spaces): ")
catalog_items = entered.split(",")
print(catalog_items)
print("count:", len(catalog_items))

View the full solution file on GitHub

Problem-4: Add and Remove Items.

Write a program that, starting from the cart items "mouse", "keyboard":

  • Task-1: insert "monitor" at index 1 and print the cart.
  • Task-2: extend the cart with ["cable", "webcam"] and print the cart.
  • Task-3: remove the last item with pop() and print what was removed.
  • Task-4: clear the cart and print it.
Expected output
['mouse', 'monitor', 'keyboard']
['mouse', 'monitor', 'keyboard', 'cable', 'webcam']
webcam
[]
Need a hint?

.insert(1, "monitor") shifts items right; .extend([...]) adds every item from another list (not the list itself, the way .append would); .pop() returns what it removes; .clear() empties the list.

Show the solution
s05_practice01_sol_lists.py
cart = ["mouse", "keyboard"]
# Problem-4 Task-1: insert "monitor" at index 1
cart.insert(1, "monitor")
print(cart)
# Problem-4 Task-2: extend the cart with two items
cart.extend(["cable", "webcam"])
print(cart)
# Problem-4 Task-3: pop the last item and print it
removed = cart.pop()
print(removed)
# Problem-4 Task-4: clear the cart
cart.clear()
print(cart)

View the full solution file on GitHub

Problem-5: Find, Copy, and Reorder.

Write a program that, starting from the order statuses "pending", "shipped", "pending", "delivered":

  • Task-1: print the index of "shipped".
  • Task-2: print how many times "pending" appears.
  • Task-3: make a copy of the list, append "returned" to the copy only, then print the original list and the copy.
  • Task-4: reverse the original list and print it.
Expected output
1
2
['pending', 'shipped', 'pending', 'delivered']
['pending', 'shipped', 'pending', 'delivered', 'returned']
['delivered', 'pending', 'shipped', 'pending']
Need a hint?

.index() and .count() only read, they do not change the list; .copy() makes a separate list, so appending to the copy leaves the original untouched; .reverse() flips the order in place.

Show the solution
s05_practice01_sol_lists.py
order_statuses = ["pending", "shipped", "pending", "delivered"]
# Problem-5 Task-1: print the index of "shipped"
print(order_statuses.index("shipped"))
# Problem-5 Task-2: count how many times "pending" appears
print(order_statuses.count("pending"))
# Problem-5 Task-3: copy the list, append to the copy only, print both
statuses_copy = order_statuses.copy()
statuses_copy.append("returned")
print(order_statuses)
print(statuses_copy)
# Problem-5 Task-4: reverse the original list
order_statuses.reverse()
print(order_statuses)

View the full solution file on GitHub

Problem-6: Slice and Membership.

Write a program that, for the price list 15, 30, 45, 60, 75:

  • Task-1: print the slice from index 1 up to (but not including) index 4.
  • Task-2: print whether 45 is in the list.
  • Task-3: print whether 99 is not in the list.
Expected output
[30, 45, 60]
True
True
Need a hint?

A slice price_list[1:4] stops BEFORE index 4; in and not in give a bool.

Show the solution
s05_practice01_sol_lists.py
price_list = [15, 30, 45, 60, 75]
# Problem-6 Task-1: print the slice from index 1 to 4
print(price_list[1:4])
# Problem-6 Task-2: print whether 45 is in the list
print(45 in price_list)
# Problem-6 Task-3: print whether 99 is not in the list
print(99 not in price_list)

View the full solution file on GitHub

Problem-7: Nested Lists.

Write a program that, starting from the order table order_rows = [["mouse", 25], ["keyboard", 45], ["monitor", 120]] (each inner list is one [product, price] row):

  • Task-1: print the whole first row.
  • Task-2: print the product name from the first row.
  • Task-3: print the price from the last row.
Expected output
['mouse', 25]
mouse
120
Need a hint?

order_rows[0] is the whole first row (an inner list); index twice - order_rows[0][0] is the product name, order_rows[2][1] is the price in the last row.

Show the solution
s05_practice01_sol_lists.py
order_rows = [["mouse", 25], ["keyboard", 45], ["monitor", 120]]
# Problem-7 Task-1: print the whole first row
print(order_rows[0])
# Problem-7 Task-2: print the product name from the first row
print(order_rows[0][0])
# Problem-7 Task-3: print the price from the last row
print(order_rows[2][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 (create, index, len, immutable, count, index, slice, in / not in, packing, one-item tuple, unpack, swap, list inside a tuple).

Problem-1: A Product Row.

Write a program that, for the product row product = ("Mouse", 25, "SKU100") (name, price, sku):

  • Task-1: print the name (first item), the sku (last item, negative index), and how many fields it has.
  • Task-2: unpack the row into name, price, sku and print Mouse costs 25.
Expected output
Mouse
SKU100
3
Mouse costs 25
Need a hint?

Read by index (product[0], product[-1]) and count fields with len(), then unpack name, price, sku = product - one name per value, in order.

Show the solution
s05_practice02_sol_tuples.py
product = ("Mouse", 25, "SKU100")
# Problem-1 Task-1: print name, sku, and field count
print(product[0])
print(product[-1])
print(len(product))
# Problem-1 Task-2: unpack the row and print name costs price
name, price, sku = product
print(name, "costs", price)

View the full solution file on GitHub

Problem-2: Product Ratings.

Write a program that, for the star ratings ratings = (5, 4, 5, 3, 5, 4, 5):

  • Task-1: print how many 5-star ratings there are, and the position of the first 3-star rating.
  • Task-2: print the first three ratings (a slice); then the last rating two ways: as a one-item tuple (ratings[-1:]) and as a plain number (ratings[-1]).
  • Task-3: check that a 3-star rating is in the ratings (in), and that a 1-star rating is not (not in).
Expected output
4
3
(5, 4, 5)
(5,)
5
True
True
Need a hint?

.count() and .index() are the only two methods a tuple has; a slice ratings[0:3] gives a tuple, ratings[-1:] a one-item tuple, ratings[-1] a plain number, and in / not in give a bool.

Show the solution
s05_practice02_sol_tuples.py
ratings = (5, 4, 5, 3, 5, 4, 5)
# Problem-2 Task-1: count 5-star and find position of the first 3-star
print(ratings.count(5))
print(ratings.index(3))
# Problem-2 Task-2: slice the first three, then the last two ways
print(ratings[0:3])
print(ratings[-1:])
print(ratings[-1])
# Problem-2 Task-3: membership checks with in and not in
print(3 in ratings)
print(1 not in ratings)

View the full solution file on GitHub

Problem-3: Build Tuples.

Write a program that:

  • Task-1: build a product row row from the name Keyboard and the price 45, writing no brackets around them (packing), and print it.
  • Task-2: make a one-item tuple holding just the price 45 (a trailing comma is required), and a plain (45) with no comma; print both type names.
Expected output
('Keyboard', 45)
tuple int
Need a hint?

The commas make the tuple: row = "Keyboard", 45; a one-item tuple NEEDS the comma (45,), while (45) is just the int - check with type(x).__name__.

Show the solution
s05_practice02_sol_tuples.py
# Problem-3 Task-1: pack a row without brackets
row = "Keyboard", 45
print(row)
# Problem-3 Task-2: one-item tuple vs plain value, print both type names
one_price = (45,)
not_a_tuple = (45)
print(type(one_price).__name__, type(not_a_tuple).__name__)

View the full solution file on GitHub

Problem-4: Fix Swapped Prices.

Write a program that, for prices = (45, 25) (the mouse and keyboard prices, entered the wrong way round):

  • Task-1: unpack prices into mouse and keyboard, then swap them in one line.
  • Task-2: since a tuple cannot change, pack the corrected order into a new tuple new_prices and print it.
  • Task-3: print the original prices tuple to show it did not change.
Expected output
(25, 45)
(45, 25)
Need a hint?

Unpack mouse, keyboard = prices, swap in one line mouse, keyboard = keyboard, mouse, then build a NEW tuple new_prices = (mouse, keyboard); printing prices again shows the original never changed.

Show the solution
s05_practice02_sol_tuples.py
prices = (45, 25)
# Problem-4 Task-1: unpack then swap in one line
mouse, keyboard = prices
mouse, keyboard = keyboard, mouse
# Problem-4 Task-2: build a new corrected tuple and print it
new_prices = (mouse, keyboard)
print(new_prices)
# Problem-4 Task-3: print the original to show it is unchanged
print(prices)

View the full solution file on GitHub

Problem-5: An Order's Item List.

Write a program that, for the order order = ("SKU100", ["mouse", "pad"]) (a fixed sku and a changeable list of items):

  • Task-1: add "cable" to the items list and print the order.
  • Task-2: clear the items list, then add "keyboard" and "monitor", and print the order.
  • Task-3: print the sku (order[0]) to show the fixed part is unchanged.
Expected output
('SKU100', ['mouse', 'pad', 'cable'])
('SKU100', ['keyboard', 'monitor'])
SKU100
Need a hint?

The tuple slot is fixed but order[1] is a LIST, so .append() and .clear() still work on it; order[0] (the sku) stays put.

Show the solution
s05_practice02_sol_tuples.py
order = ("SKU100", ["mouse", "pad"])
# Problem-5 Task-1: append to the inner items list and print the order
order[1].append("cable")
print(order)
# Problem-5 Task-2: clear the list, add two items, print the order
order[1].clear()
order[1].append("keyboard")
order[1].append("monitor")
print(order)
# Problem-5 Task-3: print the sku to show the fixed part is unchanged
print(order[0])

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 (create, look up by key, add/update, .update(), len, .get() with a default, empty then fill, .keys()/.values()/.items(), in / not in, del / .pop(), a list value, a nested dict, list of dicts, input()).

Problem-1: Build and Grow a Product Record.

Write a program that, for a product dictionary with "name" set to "Wireless Mouse" and "price" set to 25:

  • Task-1: print the name.
  • Task-2: update the price to 20.
  • Task-3: add a "brand" of "Logix".
  • Task-4: use .update() to set "stock" to 100 and "price" to 22 in one call.
  • Task-5: print how many fields the product has, then print the whole product.
Expected output
Wireless Mouse
4
{'name': 'Wireless Mouse', 'price': 22, 'brand': 'Logix', 'stock': 100}
Need a hint?

Look up a value by key with product["name"]; assign to a key to UPDATE it (product["price"] = 20) or ADD a new one (product["brand"] = "Logix"); .update({...}) sets several pairs at once; len(product) counts the key-value pairs.

Show the solution
s05_practice03_sol_dictionaries.py
product = {"name": "Wireless Mouse", "price": 25}
# Problem-1 Task-1: print the name
print(product["name"])
# Problem-1 Task-2: update the price to 20
product["price"] = 20
# Problem-1 Task-3: add a "brand" of "Logix"
product["brand"] = "Logix"
# Problem-1 Task-4: use .update() to set stock and price at once
product.update({"stock": 100, "price": 22})
# Problem-1 Task-5: print the field count, then the whole product
print(len(product))
print(product)

View the full solution file on GitHub

Problem-2: Safe Lookup and an Empty Cart.

Write a program that:

  • Task-1: for a product dictionary with "name" set to "Mouse" and "price" set to 25, print the value for the missing key "weight", falling back to "unknown".
  • Task-2: build an empty cart dictionary, add "item1" set to "Mouse" and "item2" set to "Keyboard", then print the cart.
Expected output
unknown
{'item1': 'Mouse', 'item2': 'Keyboard'}
Need a hint?

.get("weight", "unknown") returns the default instead of a KeyError for a missing key; start from an empty cart = {} and add pairs by assigning to new keys, like cart["item1"] = "Mouse".

Show the solution
s05_practice03_sol_dictionaries.py
# Problem-2 Task-1: safe lookup of a missing key with a fallback
product = {"name": "Mouse", "price": 25}
print(product.get("weight", "unknown"))
# Problem-2 Task-2: build an empty cart, add two items, print it
cart = {}
cart["item1"] = "Mouse"
cart["item2"] = "Keyboard"
print(cart)

View the full solution file on GitHub

Problem-3: Inspect a Record.

Write a program that, for a product dictionary with "name" set to "Mouse", "price" set to 25, and "brand" set to "Logix":

  • Task-1: print the list of keys.
  • Task-2: print the list of values.
  • Task-3: print the list of (key, value) pairs.
Expected output
['name', 'price', 'brand']
['Mouse', 25, 'Logix']
[('name', 'Mouse'), ('price', 25), ('brand', 'Logix')]
Need a hint?

list(product.keys()) and list(product.values()) turn the key and value VIEWS into plain lists; list(product.items()) gives each pair as a (key, value) tuple.

Show the solution
s05_practice03_sol_dictionaries.py
product = {"name": "Mouse", "price": 25, "brand": "Logix"}
# Problem-3 Task-1: print the list of keys
print(list(product.keys()))
# Problem-3 Task-2: print the list of values
print(list(product.values()))
# Problem-3 Task-3: print the list of (key, value) pairs
print(list(product.items()))

View the full solution file on GitHub

Problem-4 (Write a Program): Price Lookup.

Write a program that, for a prices dictionary with "mouse" set to 25 and "keyboard" set to 45, asks for a product name (typed in ANY capitalization) and prints that product's price, or Not Found when the product is not in the dictionary.

Example run
Enter product name for price check: Keyboard
45
Need a hint?

prices.get(product_name.lower(), "Not Found") is the safe lookup - .lower() folds any capitalization to the lowercase keys, and .get() returns the default for an unknown product instead of raising a KeyError.

Show the solution
s05_practice03_sol_dictionaries.py
# Problem-4: read a product name and print its price or "Not Found"
prices = {"mouse": 25, "keyboard": 45}
product_name = input("Enter product name for price check: ")
print(prices.get(product_name.lower(), "Not Found"))

View the full solution file on GitHub

Problem-5: Remove Fields, Then Check.

Write a program that, for a product dictionary with "name" set to "Mouse", "price" set to 25, and "old" set to True:

  • Task-1: remove "old" with del.
  • Task-2: remove "price" with .pop(), keeping its value; print the product, then the removed price.
  • Task-3: print whether "name" is a key in the product, and whether "price" is not a key.
Expected output
{'name': 'Mouse'}
25
True
True
Need a hint?

del product["old"] just discards a pair; product.pop("price") removes it AND returns its value; in / not in test the KEYS, as in "name" in product.

Show the solution
s05_practice03_sol_dictionaries.py
product = {"name": "Mouse", "price": 25, "old": True}
# Problem-5 Task-1: remove "old" with del
del product["old"]
# Problem-5 Task-2: pop "price" keeping its value, print product then price
removed_price = product.pop("price")
print(product)
print(removed_price)
# Problem-5 Task-3: check key membership with in and not in
print("name" in product)
print("price" not in product)

View the full solution file on GitHub

Problem-6: Records That Hold More.

Write a program that:

  • Task-1: for a product dictionary with "name" set to "Mouse" and "tags" set to the list ["wireless", "usb"], print the first tag, then append "ergonomic" and print the tags.
  • Task-2: for a product dictionary with "name" set to "Mouse" and "seller" set to the dictionary {"city": "Delhi", "rating": 5}, print the seller's city.
  • Task-3: for a catalog list holding {"name": "Mouse", "price": 25} and {"name": "Keyboard", "price": 45}, print the first product's name, then the second product's price.
Expected output
wireless
['wireless', 'usb', 'ergonomic']
Delhi
Mouse
45
Need a hint?

A value can be a LIST - product["tags"][0] indexes it and .append() grows it; a value can be a NESTED dict - chain product["seller"]["city"]; a list of dicts is a table - reach in with catalog[0]["name"].

Show the solution
s05_practice03_sol_dictionaries.py
# Problem-6 Task-1: a list value, so read the first tag, append one, print tags
product = {"name": "Mouse", "tags": ["wireless", "usb"]}
print(product["tags"][0])
product["tags"].append("ergonomic")
print(product["tags"])
# Problem-6 Task-2: a nested dict value, so read the seller's city
product = {"name": "Mouse", "seller": {"city": "Delhi", "rating": 5}}
print(product["seller"]["city"])
# Problem-6 Task-3: a list of product dicts, so read a name and a price
catalog = [{"name": "Mouse", "price": 25}, {"name": "Keyboard", "price": 45}]
print(catalog[0]["name"])
print(catalog[1]["price"])

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 (create, unique, len, sorted(), empty set() vs {}, set(list) dedup, in / not in, .add(), .update(), .discard(), union |, intersection &, difference -, symmetric difference ^, input()). A set has no order, so every set is printed via sorted().

Problem-1: Unique Categories.

Write a program that, for the category list ["audio", "video", "audio", "gaming", "video"]:

  • Task-1: build a set from the list, then print how many UNIQUE categories there are.
  • Task-2: print the unique categories in sorted order.
Expected output
3
['audio', 'gaming', 'video']
Need a hint?

set(categories) drops the duplicates; len() counts the uniques and sorted() prints them in a stable order, because a set has no order.

Show the solution
s05_practice04_sol_sets.py
categories = ["audio", "video", "audio", "gaming", "video"]
# Problem-1 Task-1: build a set and print the unique count
unique = set(categories)
print(len(unique))
# Problem-1 Task-2: print the unique categories sorted
print(sorted(unique))

View the full solution file on GitHub

Problem-2: The Empty-Set Trap.

Write a program that:

  • Task-1: make an empty cart with set() and print its type.
  • Task-2: print the type of {} to show it is a dictionary, not a set.
Expected output
<class 'set'>
<class 'dict'>
Need a hint?

An empty set is set() - type(set()) is set, but type({}) is dict, because {} on its own builds a dictionary.

Show the solution
s05_practice04_sol_sets.py
# Problem-2 Task-1: make an empty set and print its type
empty_cart = set()
print(type(empty_cart))
# Problem-2 Task-2: print the type of {} to show it is a dict
print(type({}))

View the full solution file on GitHub

Problem-3: Grow and Shrink a Tag Set.

Write a program that, for the tag set {"audio", "video"}:

  • Task-1: add "gaming" with .add(), bulk-add ["mobile", "audio"] with .update(), discard "video" and discard "toys" (not present), then print the sorted tags.
  • Task-2: print whether "audio" is in the tags, and whether "video" is not in the tags.
Expected output
['audio', 'gaming', 'mobile']
True
True
Need a hint?

.add() adds one value, .update([...]) adds several at once, and .discard() removes safely (no error if the value is missing); in / not in test membership.

Show the solution
s05_practice04_sol_sets.py
tags = {"audio", "video"}
# Problem-3 Task-1: add one tag, then bulk-add more
tags.add("gaming")
tags.update(["mobile", "audio"])
# Problem-3 Task-2: discard two tags, print the sorted tags
tags.discard("video")
tags.discard("toys")
print(sorted(tags))
# Problem-3 Task-3: membership checks with in and not in
print("audio" in tags)
print("video" not in tags)

View the full solution file on GitHub

Problem-4 (Write a Program): Brand Check.

Write a program that, for the brand set {"sony", "bose", "jbl"}, asks for a brand name (typed in ANY capitalization) and prints True if the store carries it, else False.

Example run
Enter a brand to check: Sony
True
Need a hint?

brand.lower() in brands folds the typed brand to lowercase, then in returns True or False for whether the store carries it.

Show the solution
s05_practice04_sol_sets.py
# Problem-4: read a brand and print whether the store carries it
brands = {"sony", "bose", "jbl"}
brand = input("Enter a brand to check: ")
print(brand.lower() in brands)

View the full solution file on GitHub

Problem-5: Category Set Math.

Write a program that, for electronics = {"audio", "video", "gaming"} and clearance = {"video", "gaming", "toys"}:

  • Task-1: print the sorted union (categories in either set).
  • Task-2: print the sorted intersection (in both).
  • Task-3: print the sorted difference (only in electronics).
  • Task-4: print the sorted symmetric difference (in exactly one set).
Expected output
['audio', 'gaming', 'toys', 'video']
['gaming', 'video']
['audio']
['audio', 'toys']
Need a hint?

| is union (in either), & is intersection (in both), - is difference (only the first), and ^ is symmetric difference (in exactly one); wrap each result in sorted().

Show the solution
s05_practice04_sol_sets.py
electronics = {"audio", "video", "gaming"}
clearance = {"video", "gaming", "toys"}
# Problem-5 Task-1: print the sorted union
print(sorted(electronics | clearance))
# Problem-5 Task-2: print the sorted intersection
print(sorted(electronics & clearance))
# Problem-5 Task-3: print the sorted difference (only in electronics)
print(sorted(electronics - clearance))
# Problem-5 Task-4: print the sorted symmetric difference
print(sorted(electronics ^ clearance))

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 workshop 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

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

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