Write concise, readable list transformations and lazy generators in Python
Quick Answer
A list comprehension `[expr for item in iterable if condition]` builds a new list in one readable line. A generator expression `(expr for item in iterable)` does the same but lazily — ideal for large datasets.
1# Basic list comprehension
2squares = [x ** 2 for x in range(10)]
3# [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
4
5# With condition (filter)
6evens = [x for x in range(20) if x % 2 == 0]
7# [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
8
9# Transform strings
10names = ['alice', 'bob', 'charlie']
11upper = [name.capitalize() for name in names]
12# ['Alice', 'Bob', 'Charlie']
13
14# Flatten a 2D list
15matrix = [[1, 2], [3, 4], [5, 6]]
16flat = [num for row in matrix for num in row]
17# [1, 2, 3, 4, 5, 6]
18
19# Dictionary comprehension
20word_lengths = {word: len(word) for word in names}
21# {'alice': 5, 'bob': 3, 'charlie': 7}
22
23# Generator expression (memory efficient)
24total = sum(x ** 2 for x in range(1_000_000))List comprehensions are one of Python's most powerful and idiomatic features. They let you build new lists by applying an expression to each item in an iterable, optionally filtering items with a condition — all in a single, readable line. Generator expressions do the same but lazily, making them memory-efficient for large datasets.
Yes — list comprehensions are generally 10–20% faster than equivalent for loops with `.append()` because the list-building is optimised at the bytecode level. Generator expressions are even more memory-efficient for large datasets.
This free python code snippet for list comprehensions & generator expressions is production-ready and copy-paste friendly. Whether you are building a web app, API, or frontend interface, this beginner-level example will help you implement list comprehensions & generator expressions quickly and correctly.
All snippets in the Snippetly library follow python best practices and are tested for real-world use. You can adapt this code to work with React, Vue, Node.js, or any project that uses python.
Organise your team's code snippets with Snippetly. Share knowledge and boost productivity across your organisation.