Part 04 / Stage 1
Data structures
Goal: Store and work with groups of data using lists, tuples, sets and dictionaries, and pick the right one for the job. Time: ~1 hour
What you will learn
list: create, index, slice and the main methodstuple: immutability, packing / unpacking,a, *rest = ...set: unique items and set maths (union, intersection, difference)dict: keys, values, items,get,update,del, looping, nested dicts- Slicing deep-dive: step and reverse
- Mutability and copying: aliasing,
.copy(), shallow vs deep copy - Basic comprehensions (list, dict, set) with a condition
- The
collectionstoolbox:Counter,defaultdict,deque - How to choose the right structure
- A note on the
arraymodule
Topics in this part
Practice
Python workbench โ write and run code here
Press Run and Python 3.14 loads right in your browser (a one-time download of about 15 MB; after that it works offline). Your code never leaves this page. input() opens a small prompt window.
Try each one yourself first. Use fixed sample data in your code, so the program runs without typing anything.
Exercise 1: Cricket scores (list)
Scenario: You track a batter's runs in the last 7 matches.
What to do: Start with runs = [45, 12, 78, 0, 101, 33, 56].
- Print the highest, lowest and average (1 decimal).
- Print the top 3 scores (highest first) without changing
runs. - Print the scores of the last 3 matches using a slice.
- Count how many 50+ scores there were.
Sample output:
Highest: 101, Lowest: 0, Average: 46.4
Top 3: [101, 78, 56]
Last 3 matches: [101, 33, 56]
50+ scores: 3
๐ก Hint: Use max(), min(), sum() and len() (section 1, "Handy built-ins"). Then sorted(runs, reverse=True)[:3] and runs[-3:].
Show the solution to Exercise 1
"""Exercise 1: Cricket scores with a list.
Run: python ex01.py (macOS/Linux: python3 ex01.py)
"""
runs = [45, 12, 78, 0, 101, 33, 56]
average = sum(runs) / len(runs)
print(f"Highest: {max(runs)}, Lowest: {min(runs)}, Average: {average:.1f}")
print(f"Top 3: {sorted(runs, reverse=True)[:3]}") # runs is not changed
print(f"Last 3 matches: {runs[-3:]}")
fifties = 0 # counter pattern
for score in runs:
if score >= 50:
fifties += 1
print(f"50+ scores: {fifties}")
Exercise 2: Min, max and swap (tuple)
Scenario: A weather app shows the coldest and hottest days.
What to do: Start with temps = [31, 29, 35, 33].
- Store the lowest and highest value in a tuple
coldest_hottest = (lowest, highest). Unpack it into two variables and print them. - Use
today, *rest = temps, then printtodayandrest. - Swap
morning = "tea"andevening = "coffee"in one line.
Sample output:
Coldest: 29, Hottest: 35
Today: 31, Rest: [29, 35, 33]
morning=coffee evening=tea
๐ก Hint: (min(temps), max(temps)) makes the tuple; low, high = coldest_hottest unpacks it.
Show the solution to Exercise 2
"""Exercise 2: Tuples - packing, unpacking, star unpacking, swap.
Run: python ex02.py (macOS/Linux: python3 ex02.py)
"""
temps = [31, 29, 35, 33]
coldest_hottest = (min(temps), max(temps)) # pack into a tuple
low, high = coldest_hottest # unpack
print(f"Coldest: {low}, Hottest: {high}")
today, *rest = temps
print(f"Today: {today}, Rest: {rest}")
morning, evening = "tea", "coffee"
morning, evening = evening, morning # swap in one line
print(f"morning={morning} evening={evening}")
Exercise 3: Common friends (set)
Scenario: A social app shows mutual friends.
What to do: With asha = {"Ravi", "Meena", "Karan", "Divya"} and ravi = {"Asha", "Meena", "Divya", "Arjun"}, print (sorted):
- Mutual friends
- People only Asha knows
- Everyone in both lists
- Friend suggestions for Asha: Ravi's friends she doesn't know (not counting herself)
Sample output:
Mutual: ['Divya', 'Meena']
Only Asha: ['Karan', 'Ravi']
All: ['Arjun', 'Asha', 'Divya', 'Karan', 'Meena', 'Ravi']
Suggest to Asha: ['Arjun']
๐ก Hint: &, -, |. For suggestions: ravi - asha - {"Asha"}.
Show the solution to Exercise 3
"""Exercise 3: Mutual friends with sets.
Run: python ex03.py (macOS/Linux: python3 ex03.py)
"""
asha = {"Ravi", "Meena", "Karan", "Divya"}
ravi = {"Asha", "Meena", "Divya", "Arjun"}
print(f"Mutual: {sorted(asha & ravi)}")
print(f"Only Asha: {sorted(asha - ravi)}")
print(f"All: {sorted(asha | ravi)}")
print(f"Suggest to Asha: {sorted(ravi - asha - {'Asha'})}")
Exercise 4: Word frequency (dict)
Scenario: A review site wants the most used words in a review.
What to do: For review = "good food good service bad parking good price":
- Count each word in a dict.
- Print words used more than once.
- Print the most common word and its count.
Sample output:
{'good': 3, 'food': 1, 'service': 1, 'bad': 1, 'parking': 1, 'price': 1}
Repeated: ['good']
Most common: good (3)
๐ก Hint: counts[word] = counts.get(word, 0) + 1.
Show the solution to Exercise 4
"""Exercise 4: Word frequency with a dict.
Run: python ex04.py (macOS/Linux: python3 ex04.py)
"""
review = "good food good service bad parking good price"
counts = {}
for word in review.split():
counts[word] = counts.get(word, 0) + 1
print(counts)
repeated = [word for word, n in counts.items() if n > 1]
print(f"Repeated: {repeated}")
top_word, top_count = "", 0 # search for the max
for word, n in counts.items():
if n > top_count:
top_word, top_count = word, n
print(f"Most common: {top_word} ({top_count})")
Exercise 5: Shop inventory (nested dict)
Scenario: A kirana shop keeps its stock in a nested dict. Starting data:
inventory = {
"sugar": {"price": 45, "qty": 20},
"salt": {"price": 25, "qty": 0},
"oil": {"price": 180, "qty": 8},
}
What to do:
- Sell 3 oil (reduce
qty). - Add a new item
"tea"with price 120, qty 15. - Print items that are out of stock.
- Print the total stock value (price ร qty for all items).
Sample output:
Out of stock: ['salt']
Total stock value: โน3,600
๐ก Hint: inventory["oil"]["qty"] -= 3, then loop with .items(). Print the total with f"โน{total:,}" to get the comma (Part 2).
Show the solution to Exercise 5
"""Exercise 5: Kirana shop inventory with a nested dict.
Run: python ex05.py (macOS/Linux: python3 ex05.py)
"""
inventory = {
"sugar": {"price": 45, "qty": 20},
"salt": {"price": 25, "qty": 0},
"oil": {"price": 180, "qty": 8},
}
inventory["oil"]["qty"] -= 3 # sold 3 oil
inventory["tea"] = {"price": 120, "qty": 15} # new item
out_of_stock = [item for item, info in inventory.items() if info["qty"] == 0]
print(f"Out of stock: {out_of_stock}")
total_value = 0 # accumulator
for item, info in inventory.items():
total_value += info["price"] * info["qty"]
print(f"Total stock value: โน{total_value:,}")
Exercise 6: Comprehension practice
Scenario: An exam result sheet. Starting data:
marks = {"Asha": 88, "Ravi": 35, "Meena": 72, "Karan": 39, "Divya": 95}
What to do (one comprehension each):
- List of names who passed (40 or more).
- Dict of name โ
"Pass"/"Fail". - Set of first letters of all names (print it sorted).
- List of marks after adding 5 grace marks, but max 100.
Sample output:
Passed: ['Asha', 'Meena', 'Divya']
Result: {'Asha': 'Pass', 'Ravi': 'Fail', 'Meena': 'Pass', 'Karan': 'Fail', 'Divya': 'Pass'}
Initials: ['A', 'D', 'K', 'M', 'R']
With grace: [93, 40, 77, 44, 100]
๐ก Hint: You can use a conditional expression inside: {n: "Pass" if m >= 40 else "Fail" for n, m in marks.items()}.
Show the solution to Exercise 6
"""Exercise 6: List, dict and set comprehensions.
Run: python ex06.py (macOS/Linux: python3 ex06.py)
"""
marks = {"Asha": 88, "Ravi": 35, "Meena": 72, "Karan": 39, "Divya": 95}
passed = [name for name, m in marks.items() if m >= 40]
result = {name: "Pass" if m >= 40 else "Fail" for name, m in marks.items()}
initials = {name[0] for name in marks}
with_grace = [min(m + 5, 100) for m in marks.values()]
print(f"Passed: {passed}")
print(f"Result: {result}")
print(f"Initials: {sorted(initials)}")
print(f"With grace: {with_grace}")
Exercise 7: Class report card (everything together)
Scenario: A teacher has raw data as a list of tuples: (name, subject, marks).
Starting data:
records = [
("Asha", "maths", 90), ("Asha", "science", 85),
("Ravi", "maths", 60), ("Ravi", "science", 72),
("Meena", "maths", 95), ("Meena", "science", 91),
("Ravi", "english", 66),
]
What to do:
- Build a nested dict:
{name: {subject: marks}}. - Find the set of all subjects.
- Print each student's total and average, sorted by total (highest first).
- Make a deep copy of the report, add 5 bonus marks to every score in the copy, and show the original did not change.
Sample output:
Subjects: ['english', 'maths', 'science']
Ravi total=198 avg=66.0
Meena total=186 avg=93.0
Asha total=175 avg=87.5
Original Asha: {'maths': 90, 'science': 85}
Bonus Asha: {'maths': 95, 'science': 90}
๐ก Hint: Check if name not in report: and create an empty inner dict first. You will need import copy for copy.deepcopy(). For sorting by total, build a list of (total, name) tuples and sort it with reverse=True (tuples compare by their first item: section 2).
Show the solution to Exercise 7
"""Exercise 7: Class report card from raw records.
Run: python ex07.py (macOS/Linux: python3 ex07.py)
"""
import copy # (imports are covered in Part 7)
records = [
("Asha", "maths", 90), ("Asha", "science", 85),
("Ravi", "maths", 60), ("Ravi", "science", 72),
("Meena", "maths", 95), ("Meena", "science", 91),
("Ravi", "english", 66),
]
# 1. Nested dict {name: {subject: marks}}
report = {}
for name, subject, marks in records:
if name not in report:
report[name] = {}
report[name][subject] = marks
# 2. All subjects (set comprehension)
subjects = {subject for _, subject, _ in records}
print(f"Subjects: {sorted(subjects)}")
# 3. Totals, sorted highest first
ranking = []
for name, scores in report.items():
ranking.append((sum(scores.values()), name))
ranking.sort(reverse=True)
for total, name in ranking:
average = total / len(report[name])
print(f"{name:<7} total={total} avg={average:.1f}")
# 4. Deep copy with bonus marks
bonus_report = copy.deepcopy(report)
for scores in bonus_report.values():
for subject in scores:
scores[subject] += 5
print(f"\nOriginal Asha: {report['Asha']}")
print(f"Bonus Asha: {bonus_report['Asha']}")
Exercise 8: Canteen end-of-day board (collections)
Scenario: The canteen logs every sale as a (customer, item) pair and wants three things on the evening board: the top sellers, each customer's purchases, and the last three sales.
sales = [
("Asha", "chai"), ("Ravi", "samosa"), ("Meena", "chai"),
("Asha", "samosa"), ("Ravi", "chai"), ("Asha", "chai"),
("Meena", "juice"),
]
What to do:
- Use a
Counterto print the two best-selling items with their counts. - Use a
defaultdict(list)to group items by customer, and print each customer's list (sorted by name). - Use a
deque(maxlen=3)to show only the last three sales as"name-item"strings.
Sample output:
Top sellers: [('chai', 4), ('samosa', 2)]
Asha: ['chai', 'samosa', 'chai']
Meena: ['chai', 'juice']
Ravi: ['samosa', 'chai']
Last 3 sales: ['Ravi-chai', 'Asha-chai', 'Meena-juice']
๐ก Hint: Counter(item for _, item in sales) counts straight from a generator expression (section 7). most_common(2) gives the top two. For the board, append every sale to the deque and let maxlen do the forgetting.
Show the solution to Exercise 8
"""Exercise 8: Canteen end-of-day board (collections).
Run: python ex08.py (macOS/Linux: python3 ex08.py)
"""
from collections import Counter, defaultdict, deque
sales = [
("Asha", "chai"), ("Ravi", "samosa"), ("Meena", "chai"),
("Asha", "samosa"), ("Ravi", "chai"), ("Asha", "chai"),
("Meena", "juice"),
]
# 1. Top two sellers โ count items straight from a generator expression
tally = Counter(item for _, item in sales)
print("Top sellers:", tally.most_common(2))
# 2. Group purchases by customer
by_customer = defaultdict(list)
for name, item in sales:
by_customer[name].append(item)
for name in sorted(by_customer):
print(f"{name}: {by_customer[name]}")
# 3. The "last 3 sales" board โ maxlen does the forgetting for us
screen = deque(maxlen=3)
for name, item in sales:
screen.append(f"{name}-{item}")
print("Last 3 sales:", list(screen))
Common mistakes
| Mistake | Why it is wrong | Fix |
|---|---|---|
lst = lst.sort() |
sort() returns None, list is lost |
lst.sort() or lst = sorted(lst) |
empty = {} for a set |
{} is an empty dict |
empty = set() |
t = ("one") for a tuple |
brackets alone don't make a tuple | t = ("one",) |
d["key"] when key may be missing |
KeyError |
d.get("key", default) |
b = a to copy a list |
both names share one list | b = a.copy() |
.copy() on a list of lists |
inner lists are still shared | copy.deepcopy(a) |
| Changing a list while looping over it | items get skipped | loop over a copy, or build a new list |
| Using a list as a dict key | lists are mutable, TypeError |
use a tuple |
for i in range(len(names)): print(names[i]) |
works, but harder to read | for name in names: or enumerate(names) |
Quick recap
list= ordered + changeable;tuple= ordered + fixed.set= unique items, fastin, set maths with| & -.dict= key โ value; use.get()for safe lookups.- Slicing
[start:stop:step];[::-1]reverses. b = ais an alias;.copy()is shallow;copy.deepcopy()copies everything.- Comprehensions build lists, dicts and sets in one readable line.
Countercounts,defaultdictgroups,dequequeues.- Prefer lists over the
arraymodule for daily work.
Checklist
- I can add, remove and sort items in a list.
- I can unpack a tuple, including
first, *rest = .... - I can remove duplicates and find common items with sets.
- I can add, update, delete and loop over a dict, including nested ones.
- I can slice with a step and reverse a sequence.
- I can count with
Counterand group withdefaultdict(list). - I can explain aliasing, shallow copy and deep copy.
- I can write a list, dict and set comprehension with a condition.
- I can choose the right structure for a problem.