Python Learning Series · @onlysamarrr · Day 20 / 30

Day 20: List Comprehension

Day 20 teaches list comprehension: [expression for item in iterable if condition] builds a list in one line. It is short and fast, but if it gets complex, a normal loop is better.

Phase: Intermediate · Reels: 96/450 – 100/450

Quick Answer

Day 20 teaches list comprehension: [expression for item in iterable if condition] builds a list in one line. It is short and fast, but if it gets complex, a normal loop is better.

What You Will Learn

Code

sq = [n * n for n in range(1, 6)]
print(sq)
evens = [n for n in range(10) if n % 2 == 0]
print(evens)
tags = ["even" if n % 2 == 0 else "odd" for n in range(3)]
print(tags)
d = {n: n * n for n in range(3)}
print(d)
total = sum(n * n for n in range(4))
print(total)

Output

[1, 4, 9, 16, 25]
[0, 2, 4, 6, 8]
['even', 'odd', 'even']
{0: 0, 1: 1, 2: 4}
14

Code Explained, Line by Line

  1. [n * n for n in range(1, 6)] builds a list of squares in one line.
  2. Adding if n % 2 == 0 keeps only items that pass the condition.
  3. ["even" if n % 2 == 0 else "odd" for n in ...] picks one of two values for each item.
  4. {n: n * n for n in ...} is a dict comprehension: it builds key: value pairs.
  5. sum(n * n for n in ...) is a generator: it totals without building a list, saving memory.
Common Mistake: A 3-level nested comprehension is unreadable. When comprehension gets complex, write a normal loop: readability comes first.

Real-Life Use

Filtering data, transforming lists and building reports use comprehensions in real code.

Practice Task: Build a list of squares from 1 to 9 using list comprehension.

Test Yourself — MCQs

Select (tick) an option, then tap Check answer to see instantly whether your answer is right or wrong, with an explanation. You can change your answer and check again.

Q1. What does [n * n for n in range(1, 4)] give?

Q2. What does [n for n in range(5) if n % 2 == 0] give?

Q3. When should you avoid comprehension?

Today's 5 Reels (from the 90-Day Plan Excel)

96/450ConceptOne line mein list
97/450Live demoCondition ke saath comprehension
98/450Common mistakeZyada complex mat banao
99/450QuizQuiz: squares list
100/450Interview / real lifeInterview: comprehension vs loop
← Day 19Day 21 →