intermediateAdvanced Topics

Advanced Comprehensions

Nested comprehensions, generator expressions, and walrus operator.

01Nested Comprehensions

Create complex data structures with nested comprehension syntax.

Python
1# Flatten a 2D list
2matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
3flat = [x for row in matrix for x in row]
4print(flat)
5
6# Dict comprehension with filtering
7scores = {"Alice": 95, "Bob": 67, "Charlie": 82, "Diana": 73}
8top = {k: v for k, v in scores.items() if v >= 80}
9print(top)
Output
[1, 2, 3, 4, 5, 6, 7, 8, 9]
{'Alice': 95, 'Charlie': 82}

02Generator Expressions

Like list comprehensions but memory-efficient — they yield items one at a time.

Python
1# Generator expression (lazy evaluation)
2sum_squares = sum(x**2 for x in range(1000000))
3print(sum_squares)
4
5# Generator function
6def fibonacci():
7 a, b = 0, 1
8 while True:
9 yield a
10 a, b = b, a + b
11
12fib = fibonacci()
13print([next(fib) for _ in range(10)])
Output
333332833333500000
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]