Python Comprehensions: List, Dict, and Set Comprehensions

Write cleaner, faster Python. Master list, dictionary, and set comprehensions with practical examples, filtering conditions, and nested loops.

Try Python Comprehensions Code

Overview

Comprehensions are one of Python's most beloved features, offering a concise and highly readable syntax for creating new collections (lists, dictionaries, and sets) from existing iterables. Rather than writing multi-line `for` loops and manually appending items, comprehensions allow you to perform the same transformation, filtering, and assignment in a single, expressive line of code.

List comprehensions are the most common variant, structured as `[expression for item in iterable if condition]`. Under the hood, Python optimizes comprehensions to run at near-C speed, often outperforming equivalent manual `for` loops because the looping is handled by the underlying interpreter. They are ideal for quick transformations—such as converting a list of Celsius temperatures to Fahrenheit, or extracting specific keys from a list of user records.

Beyond lists, Python supports Dictionary and Set comprehensions. A dictionary comprehension, defined with curly braces and key-value pairs (e.g., `{key: value for x in iterable}`), is highly useful for inverting mapping pairs or parsing metadata. Set comprehensions generate unique collections by automatically removing duplicates. While comprehensions are incredibly powerful, developers should avoid overcomplicating them; if a comprehension requires nested loops or complex conditions, a traditional `for` loop is usually easier to read and maintain.

Code Example

Demonstrates list transformations, conditional filtering, and creating a dictionary from mapping inputs.

comprehensions.py
Try in Editor
numbers = [1, 2, 3, 4, 5, 6]

# List comprehension with filter (even squares)
even_squares = [x**2 for x in numbers if x % 2 == 0]

# Set comprehension (unique word lengths)
words = ["python", "java", "ruby", "python"]
word_lengths = {len(w) for w in words}

# Dictionary comprehension (number: square)
square_map = {n: n**2 for n in numbers[:4]}

print(f"Even squares: {even_squares}")
print(f"Unique lengths: {word_lengths}")
print(f"Square mapping: {square_map}")
Terminal Output
Even squares: [4, 16, 36]
Unique lengths: {4, 6}
Square mapping: {1: 1, 2: 4, 3: 9, 4: 16}

Real-world Use Cases

  • Filtering out empty values or invalid data from logs
  • Mapping API payloads into key-value data mappings
  • Quickly formatting database rows into simple lists

Frequently Asked Questions

Are comprehensions faster than normal loops?

Yes, in most cases they are faster because the iteration is handled by optimized C code within the Python interpreter.

Should I always use comprehensions?

No. Code readability is python's priority. If the comprehension has nested logic or is longer than one or two lines, a traditional loop is preferred.

Keep Learning

Recommended Python Resources

Expand your knowledge with related interactive tutorials, cheat sheets, and code comparisons.