intermediateAdvanced Topics
Advanced Comprehensions
Nested comprehensions, generator expressions, and walrus operator.
In this lesson
01Nested Comprehensions
Create complex data structures with nested comprehension syntax.
Python
1# Flatten a 2D list2matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]3flat = [x for row in matrix for x in row]4print(flat)56# Dict comprehension with filtering7scores = {"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)45# Generator function6def fibonacci():7 a, b = 0, 18 while True:9 yield a10 a, b = b, a + b1112fib = fibonacci()13print([next(fib) for _ in range(10)])
Output
333332833333500000 [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]