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):

python
squares = []
for x in range(1, 6):
    squares.append(x ** 2)
print(squares)  # [1, 4, 9, 16, 25]

List Comprehension (1 line):

python
squares = [x**2 for x in range(1, 6)]
print(squares)  # [1, 4, 9, 16, 25]

Syntax:

python
new_list = [expression for item in iterable if condition]

1. Basic List Comprehensions (15 mins)

Try This in day10.py:

python
# 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:

text
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:

python
pairs = []
for i in [1, 2]:
    for j in ['a', 'b']:
        pairs.append((i, j))

Comprehension way:

python
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:

python
# 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:

text
['1×1=1', '1×2=2', '2×1=2', '2×2=4']

3. Dictionary & Set Comprehensions

Dict Comprehension:

python
# {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:

python
# 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

python
# "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:

text
['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):

python
# 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:

text
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)

python
# 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))  # 1

Common Mistakes & Fixe

MistakeIssueFix
for x in range(5): print(x**2)No listUse [x**2 for ...]
Wrong order in nestedWrong pairsInner loop last
Modifying list in loopUnexpectedUse 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:



Comments

Popular Posts