A
AiTechWorlds
AiTechWorlds
List, dict, set comprehensions, generator functions, yield, itertools — every lazy iteration pattern with examples.
# Traditional loop
squares = []
for x in range(10):
squares.append(x ** 2)
# List comprehension — same result, one line
squares = [x ** 2 for x in range(10)]
# [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]evens = [x for x in range(20) if x % 2 == 0]
# [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
words = ["hello", "world", "python", "code"]
long_words = [w.upper() for w in words if len(w) > 4]
# ['HELLO', 'WORLD', 'PYTHON']# Flatten 2D list
matrix = [[1,2,3],[4,5,6],[7,8,9]]
flat = [n for row in matrix for n in row]
# [1, 2, 3, 4, 5, 6, 7, 8, 9]
# 5×5 multiplication table
table = [[i * j for j in range(1, 6)] for i in range(1, 6)]# Dict comprehension
word_lengths = {word: len(word) for word in ["apple", "banana", "cherry"]}
# {'apple': 5, 'banana': 6, 'cherry': 6}
# Invert a dictionary
original = {'a': 1, 'b': 2, 'c': 3}
inverted = {v: k for k, v in original.items()}
# {1: 'a', 2: 'b', 3: 'c'}
# Set comprehension — removes duplicates
unique_lengths = {len(w) for w in ["cat", "dog", "bird", "ant", "fish"]}
# {3, 4}# List comprehension — creates full list in memory immediately
squares_list = [x**2 for x in range(1_000_000)] # 8 MB memory
# Generator expression — lazy: computes one value at a time
squares_gen = (x**2 for x in range(1_000_000)) # ~100 bytes
# Same iteration interface
total = sum(x**2 for x in range(1_000_000)) # no list ever createddef fibonacci(n):
a, b = 0, 1
for _ in range(n):
yield a # pauses here, returns a
a, b = b, a + b # resumes here on next()
for num in fibonacci(10):
print(num) # 0 1 1 2 3 5 8 13 21 34def chain(*iterables):
for it in iterables:
yield from it # delegates to sub-generator
list(chain([1,2], [3,4], [5,6])) # [1, 2, 3, 4, 5, 6]def counter(start=0):
n = start
while True:
received = yield n # can receive values with send()
n = (received or n) + 1
gen = counter(10)
next(gen) # 10 — prime the generator
next(gen) # 11
gen.send(100) # 101 — jump to 100, then +1
gen.throw(ValueError, "stop") # raise in generator
gen.close() # StopIterationimport itertools
# Infinite counter
for i in itertools.count(start=10, step=2): # 10, 12, 14, ...
if i > 20: break
# Repeat value
list(itertools.repeat("x", 4)) # ['x', 'x', 'x', 'x']
# Cycle through iterable
colors = itertools.cycle(["red", "green", "blue"])
[next(colors) for _ in range(6)] # ['red', 'green', 'blue', 'red', ...]
# Combinations and permutations
list(itertools.combinations("ABC", 2)) # [('A','B'),('A','C'),('B','C')]
list(itertools.permutations("AB", 2)) # [('A','B'),('B','A')]
list(itertools.product("AB", "12")) # [('A','1'),('A','2'),('B','1'),('B','2')]
# Chaining iterables
list(itertools.chain([1,2], [3,4], [5])) # [1, 2, 3, 4, 5]
# islice — lazy slice of any iterable
list(itertools.islice(range(100), 5, 15, 2)) # [5, 7, 9, 11, 13]
# groupby — group consecutive identical elements
data = [("a",1),("a",2),("b",3),("b",4),("c",5)]
for key, group in itertools.groupby(data, key=lambda x: x[0]):
print(key, list(group))| Approach | Memory | Speed (build) | Speed (iterate once) |
|---|---|---|---|
| List comprehension | O(n) | Fast | Fast |
| Generator expression | O(1) | Instant | Same (lazy) |
map() / filter() | O(1) | Instant | Same |
| Traditional loop | O(n) | Slowest | Comparable |
Rule: Use generators when the full list is never needed at once — pipelines, streaming, large data.
| Use Case | Best Choice |
|---|---|
| Transform small list | List comprehension |
| Filter + transform | List comprehension |
| Build a dict from pairs | Dict comprehension |
| Process line-by-line from file | Generator function |
| Infinite sequence | Generator with while True |
| Large data pipeline | Chained generators |
| One-time sum/max/min | Generator expression |
list() to cache:=) inside a comprehension without understanding scope side effectssend() — always call next() first before send()Download Python List Comprehensions & Generators
Get this note + 100s more free on Telegram
Join AiTechWorlds on Telegram and get daily AI tips, prompt engineering templates, coding resources, and exclusive content — 100% free!
No spam. Leave anytime.