Day 10: Advanced Loops & List Comprehensions – Write Pro-Level Python!
Day 10: Advanced Loops & List Comprehensions – Write Pro-Level Python!
Heyy, Day 10 is here! You’ve already crushed Variables, Operators, Strings, Lists, Tuples, Sets, Dictionaries, If-Else, and Loops. Now, Day 10 is where you go from beginner to intermediate with advanced loops and list comprehensions – the secret sauce of Python pros!
Think of it like:
Instead of writing 10 lines → 1 line Instead of copy-paste → smart, clean code
Let’s make your code short, fast, and sexy.
What Are List Comprehensions? (10 mins)
A one-liner to create a new list by transforming or filtering an existing one.
Normal way (5 lines):
squares = []
for x in range(1, 6):
squares.append(x ** 2)
print(squares) # [1, 4, 9, 16, 25]List Comprehension (1 line):
squares = [x**2 for x in range(1, 6)]
print(squares) # [1, 4, 9, 16, 25]Syntax:
new_list = [expression for item in iterable if condition]1. Basic List Comprehensions (15 mins)
Try This in day10.py:
# 1. Squares of 1 to 10
squares = [x**2 for x in range(1, 11)]
print("Squares:", squares)
# 2. Uppercase names
names = ["alice", "bob", "charlie"]
upper_names = [name.upper() for name in names]
print("Upper:", upper_names)
# 3. Even numbers only
evens = [x for x in range(10) if x % 2 == 0]
print("Evens:", evens)Output:
Squares: [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
Upper: ['ALICE', 'BOB', 'CHARLIE']
Evens: [0, 2, 4, 6, 8]2. Nested Loops in Comprehensions (15 mins)
Normal way:
pairs = []
for i in [1, 2]:
for j in ['a', 'b']:
pairs.append((i, j))Comprehension way:
pairs = [(i, j) for i in [1, 2] for j in ['a', 'b']]
print(pairs) # [(1, 'a'), (1, 'b'), (2, 'a'), (2, 'b')]Try This:
# Multiplication table (2×2)
table = [f"{i}×{j}={i*j}" for i in range(1, 3) for j in range(1, 3)]
print(table)Output:
['1×1=1', '1×2=2', '2×1=2', '2×2=4']3. Dictionary & Set Comprehensions
Dict Comprehension:
# {number: square}
squares_dict = {x: x**2 for x in range(1, 6)}
print(squares_dict) # {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}Set Comprehension:
# Unique lengths of words
words = ["hi", "hello", "python"]
lengths = {len(word) for word in words}
print(lengths) # {2, 5, 6}4. Advanced: Conditional Logic Inside
# "Positive", "Negative", or "Zero"
numbers = [5, -3, 0, 7, -1]
labels = ["Positive" if x > 0 else "Negative" if x < 0 else "Zero" for x in numbers]
print(labels)Output:
['Positive', 'Negative', 'Zero', 'Positive', 'Negative']Mini Project: Smart Data Cleaner (30–40 mins)
Let’s build a Smart Data Cleaner!
- Take list of emails
- Clean: lowercase, remove duplicates, filter valid ones
- Output: clean list + stats
Code (day10_cleaner.py):
# Smart Data Cleaner
raw_emails = [
" ALICE@GMAIL.COM ",
"bob@yahoo.com",
" alice@gmail.com ",
"charlie@invalid",
"david@company.com",
" BOB@YAHOO.COM "
]
print("Raw emails:", raw_emails)
# Step 1: Clean (strip + lowercase)
cleaned = [email.strip().lower() for email in raw_emails]
# Step 2: Remove duplicates (using set)
unique = list({email for email in cleaned})
# Step 3: Filter valid (contains @ and ends with .com)
valid = [email for email in unique if "@" in email and email.endswith(".com")]
# Stats
print(f"\nCleaned: {len(cleaned)}")
print(f"Unique: {len(unique)}")
print(f"Valid: {len(valid)}")
print("Valid emails:", valid)Output:
Raw emails: [' ALICE@GMAIL.COM ', 'bob@yahoo.com', ...]
Cleaned: 6
Unique: 4
Valid: 3
Valid emails: ['alice@gmail.com', 'bob@yahoo.com', 'david@company.com']Bonus: Generator Expression (Memory Efficient)
# For huge data – don't store in memory
squares_gen = (x**2 for x in range(1000000))
print(next(squares_gen)) # 0
print(next(squares_gen)) # 1Common Mistakes & Fixe
| Mistake | Issue | Fix |
|---|---|---|
| for x in range(5): print(x**2) | No list | Use [x**2 for ...] |
| Wrong order in nested | Wrong pairs | Inner loop last |
| Modifying list in loop | Unexpected | Use comprehension |
Day 10 Wrap-Up
You learned:
- List comprehensions (1-line lists)
- Dict & Set comprehensions
- Nested comprehensions
- Conditional expressions inside
- Built a Smart Data Cleaner
Track Progress:
Day 10 Done: Pro-level Python! 1-line magic. Doubt: When to use comprehension vs loop? Answer: Use comprehension for simple transformations. Use loop for complex logic.
Resources:
- RealPython: List Comprehensions
- W3Schools: Comprehensions
- YouTube: “Python List Comprehensions” (freeCodeCamp)



Comments
Post a Comment