Python Learning Series · @onlysamarrr · Day 20 / 30
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
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.
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)
[1, 4, 9, 16, 25]
[0, 2, 4, 6, 8]
['even', 'odd', 'even']
{0: 0, 1: 1, 2: 4}
14
Filtering data, transforming lists and building reports use comprehensions in real code.
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?
| 96/450 | Concept | One line mein list |
| 97/450 | Live demo | Condition ke saath comprehension |
| 98/450 | Common mistake | Zyada complex mat banao |
| 99/450 | Quiz | Quiz: squares list |
| 100/450 | Interview / real life | Interview: comprehension vs loop |