BeginnerPython · Lesson 6 of 8

Lists, Tuples, Dictionaries & Sets

Store groups of values, loop over them and build new ones with comprehensions.

A list is an ordered, changeable sequence: [78, 64, 91]. A tuple is like a list but cannot change: ("Biology", 85). A dict maps keys to values: {"name": "Amina", "score": 88}. A set holds unique values with fast membership checks.

Comprehensions build a new collection from an existing one in one readable line: [s for s in scores if s >= 30].

A list of dictionaries is the most common way to hold simple records in Python — much like rows in a spreadsheet.

collections_demo.pyPython
students = [
    {"name": "Amina", "form": 4, "score": 88},
    {"name": "Baraka", "form": 3, "score": 54},
    {"name": "Neema", "form": 4, "score": 71},
]

form_four = [s["name"] for s in students if s["form"] == 4]
print(form_four)                              # ['Amina', 'Neema']

average = sum(s["score"] for s in students) / len(students)
top = max(students, key=lambda s: s["score"])
print(f"Average {average:.1f}, top: {top['name']}")

by_name = {s["name"]: s["score"] for s in students}   # dict comprehension
by_name["Juma"] = 42                                  # add a key
print(by_name.get("Neema"), by_name.get("Ali", "not found"))

for name, score in by_name.items():
    print(f"{name:<8}{score:>4}")

subjects_a = {"Maths", "Physics", "Chemistry"}
subjects_b = {"Maths", "Biology"}
print(subjects_a & subjects_b, subjects_a | subjects_b)   # intersection, union

point = (3, 4)            # tuple: fixed pair
x, y = point
print((x ** 2 + y ** 2) ** 0.5)   # 5.0
Runs in your browser · Python

Key points

  • list = ordered & changeable, tuple = fixed, dict = key → value, set = unique items.
  • Comprehensions replace most build-a-list loops.
  • dict.get(key, default) avoids errors for missing keys.

Exercise

Given a list of product dictionaries (name, price, quantity), print: the names of products under 5,000 TSh, the total stock value, and a dictionary of category → number of products. Use comprehensions where possible.

Show solution

Try the exercise yourself first — then compare your approach with this one.

A list of dictionaries holds the products. A list comprehension finds the cheap names, sum over a generator adds up the stock value, max with a key finds the most expensive product, and a dictionary comprehension plus .get counts categories.

products.pyPython
products = [
    {"name": "Exercise book", "price": 1500, "quantity": 200, "category": "Stationery"},
    {"name": "Scientific calculator", "price": 35000, "quantity": 12, "category": "Electronics"},
    {"name": "Geometry set", "price": 4500, "quantity": 40, "category": "Stationery"},
    {"name": "School bag", "price": 25000, "quantity": 15, "category": "Bags"},
]

cheap = [p["name"] for p in products if p["price"] < 5000]
stock_value = sum(p["price"] * p["quantity"] for p in products)
most_expensive = max(products, key=lambda p: p["price"])

per_category = {}
for p in products:
    per_category[p["category"]] = per_category.get(p["category"], 0) + 1

print(cheap)                    # ['Exercise book', 'Geometry set']
print(f"{stock_value:,} TSh")   # 1,275,000 TSh
print(most_expensive["name"])   # Scientific calculator
print(per_category)             # {'Stationery': 2, 'Electronics': 1, 'Bags': 1}
Runs in your browser · Python

Check your understanding

  1. Which collection keeps only unique values?

  2. What does by_name.get("Ali", "not found") return if "Ali" isn't a key?

  3. What is the main difference between a list and a tuple?

  4. What does [s for s in scores if s >= 30] produce?

Ask AI