Back to all snippets
Library/Python/List Comprehensions & Generator Expressions
pythonbeginnerlistsgeneratorsfunctionalperformance

How to implement List Comprehensions & Generator Expressions in Python

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.

Code Snippet

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))

What is List Comprehensions & Generator Expressions?

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.

How It Works

  1. 1The expression before `for` is evaluated and collected for each item.
  2. 2The optional `if` clause filters items before the expression is applied.
  3. 3Nested `for` clauses allow flattening multi-dimensional lists.
  4. 4Replace `[]` with `()` to get a generator expression — it yields values one at a time instead of building the full list.

Common Use Cases

  • Data transformation - Map, filter, and reshape lists in a single expression
  • Flattening nested lists - Convert 2D lists to 1D without nested loops
  • Dictionary/set building - Create dicts and sets from existing iterables
  • Large data processing - Use generators to process millions of rows without loading into memory

Key Benefits

  • More readable and concise than equivalent for loops
  • Faster than equivalent map/filter or manual append loops
  • Generators save memory for large datasets
  • Idiomatic Python that every developer recognizes

Common Mistakes to Avoid

  • Using a list comprehension when a generator expression would do — `sum([x**2 for x in range(1_000_000)])` builds a list in memory unnecessarily; `sum(x**2 for x in range(1_000_000))` is more efficient.
  • Nesting too deeply — comprehensions with 3+ nested loops are hard to read; use a helper function instead.
  • Putting side effects in comprehensions — comprehensions are for building values, not for running side effects like printing.

Quick Tips

  • Click the "Copy" button above to copy the code to your clipboard
  • This code is production-ready and can be used in your projects immediately
  • Check out related snippets below for more python examples

Frequently Asked Questions

Are list comprehensions faster than for loops in Python?

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.

About This Python Code Snippet

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.

Tags: lists, generators, functional, performance  | Language: python  | Difficulty: beginner  | Category: Python

Build Your Own Snippet Library

Organise your team's code snippets with Snippetly. Share knowledge and boost productivity across your organisation.