π§ͺ Practice: Power Tools
Comprehensions, generators, and modules β the Module 10 toolkit, under pressure. Solutions at the bottom.
Exercise 1 β Comprehension warmups
Rewrite each loop as a one-line comprehension:
# A
result = []
for n in range(1, 11):
if n % 2 == 0:
result.append(n * n)
# B
names = ["aarav", "diya", "kabir"]
caps = []
for n in names:
caps.append(n.upper())
# C
words = ["hi", "hello", "hey", "greetings"]
short = []
for w in words:
if len(w) <= 4:
short.append(w)
Exercise 2 β The data cleaner
Given this messy list, produce a clean list of proper-cased, stripped names β one comprehension:
raw = [" aarav sharma ", "DIYA PATEL", " kabir singh ", "Meera IYER"]
# Expected: ['Aarav Sharma', 'Diya Patel', 'Kabir Singh', 'Meera Iyer']
(Hint: .title() capitalizes each word.)
Exercise 3 β Dict comprehension workout
From marks = {"Aarav": 92, "Diya": 45, "Kabir": 78, "Meera": 88}, build:
- A dict of only passing students (marks >= 50)
- A dict mapping each name to βPassβ/βFailβ
- The highest scorerβs name (no comprehension needed for this one β use max with a key!)
Exercise 4 β The lazy sequence
Write a generator function even_numbers(limit) that yields even numbers from 0 up to limit. Loop it to print evens below 12.
Exercise 5 β The module split
Create two files: utils.py containing a clean_name(name) function (strip + title-case), and main.py that imports it and processes this list:
raw = [" aarav ", "DIYA"]
# main.py prints: ['Aarav', 'Diya']
Add the if __name__ == "__main__": guard to main.py properly.
Solutions
Exercise 1:
# A
result = [n * n for n in range(1, 11) if n % 2 == 0]
# B
caps = [n.upper() for n in names]
# C
short = [w for w in words if len(w) <= 4]
Exercise 2:
clean = [name.strip().title() for name in raw]
print(clean)
Exercise 3:
marks = {"Aarav": 92, "Diya": 45, "Kabir": 78, "Meera": 88}
passing = {name: m for name, m in marks.items() if m >= 50}
# {'Aarav': 92, 'Kabir': 78, 'Meera': 88}
results = {name: ("Pass" if m >= 50 else "Fail") for name, m in marks.items()}
# {'Aarav': 'Pass', 'Diya': 'Fail', 'Kabir': 'Pass', 'Meera': 'Pass'}
topper = max(marks, key=lambda name: marks[name])
# 'Aarav'
Exercise 4:
def even_numbers(limit):
n = 0
while n < limit:
yield n
n += 2
for even in even_numbers(12):
print(even) # 0 2 4 6 8 10
Exercise 5:
# utils.py
def clean_name(name):
return name.strip().title()
# main.py
from utils import clean_name
def main():
raw = [" aarav ", "DIYA"]
clean = [clean_name(name) for name in raw]
print(clean) # ['Aarav', 'Diya']
if __name__ == "__main__":
main()
β Module 10 Checkpoint
Comprehensions compressing loops, generators streaming lazily, code split into modules. Your Python just became Pythonic.
Next module: The Ecosystem β pip, environments, requests, and Git. Where your code meets the world.