How to Use Comprehensions and Generators in Python
Demonstrate list, set, and dictionary comprehensions plus generator expressions and generator functions in one beginner-friendly script.
Python code
31 linesdef demonstrate_comprehensions_generators():
# List comprehension: transform and filter in one line
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
squares = [num ** 2 for num in numbers if num % 2 == 0]
print(f"Square of even numbers (list comprehension): {squares}")
# Set comprehension: unique values
text = "hello world"
unique_vowels = {char for char in text if char in "aeiou"}
print(f"Unique vowels (set comprehension): {sorted(unique_vowels)}")
# Dictionary comprehension: map keys to values
word_lengths = {word: len(word) for word in ["apple", "banana", "cherry"]}
print(f"Word lengths (dict comprehension): {word_lengths}")
# Generator expression: memory-efficient one-time iteration
sum_of_squares = sum(num ** 2 for num in range(1, 11))
print(f"Sum of squares 1-10 (generator): {sum_of_squares}")
# Generator function with yield
def fibonacci(limit):
a, b = 0, 1
while a < limit:
yield a
a, b = b, a + b
fib_sequence = list(fibonacci(30))
print(f"Fibonacci under 30 (generator function): {fib_sequence}")
if __name__ == "__main__":
demonstrate_comprehensions_generators()
Output
Square of even numbers (list comprehension): [4, 16, 36, 64, 100]
Unique vowels (set comprehension): ['e', 'o']
Word lengths (dict comprehension): {'apple': 5, 'banana': 6, 'cherry': 6}
Sum of squares 1-10 (generator): 385
Fibonacci under 30 (generator function): [0, 1, 1, 2, 3, 5, 8, 13, 21]
How it works
List comprehensions let you build a new list by transforming and filtering an existing iterable in a single expression — here we square only the even numbers from 1 to 10. Set comprehensions automatically remove duplicates and are great for collecting unique items, such as vowels in a string. Dictionary comprehensions map each key to a computed value, like word-length pairs for a list of fruits. Generator expressions use parentheses instead of brackets and yield values lazily, so sum(num ** 2 for num in range(1, 11)) computes the total without building an entire list in memory. Finally, generator functions use yield to pause and resume, producing a Fibonacci sequence on demand until a limit is reached.
Common mistakes
- Using square brackets instead of parentheses for generator expressions, which builds a whole list in memory
- Forgetting that `sorted()` returns a list, so set output prints as a list of characters
- Calling `list()` on an infinite generator, which never terminates
- Expecting a generator function to return values instead of using `yield`
Variations
- Use `[num ** 2 for num in numbers if num % 2 == 0]` for a list of squares of evens — same as shown
- Employ `map(str.upper, words)` with a generator to transform items lazily without a loop
Real-world use cases
- Cleaning and transforming API response fields, like extracting user emails from a JSON list of objects.
- Streaming log lines from a large file and filtering errors without loading the whole file into memory.
- Building in-memory lookup dictionaries, like mapping product IDs to price tags for fast access in a web app.
Sponsored
More from Comprehensions & generators
- Batch Rows in Chunks with a Generator in Python easy
- Build a Generator Pipeline in Python: Filter Then Map medium
- Build a lazy generator to read file lines in Python easy
- Chunk an Iterable into Batches with a Generator in Python easy
- Convert Data in Python with Comprehensions and Generators easy
- Count Data in Python with Comprehensions and Generators easy
Keep learning
Related tutorials and quizzes for this topic.