Python List, Set and Dictionary Comprehensions

Learn Python List, Set and Dictionary Comprehensions with practical examples, explanations, best practices, and real-world coding techniques.

Python comprehensions provide a concise way to create new collections from existing iterables. Instead of writing several lines of loop logic to build a list, set, or dictionary, a comprehension allows the transformation to be expressed in a compact and readable form.

Python supports list comprehensions, set comprehensions, and dictionary comprehensions. They follow a similar idea, but each produces a different collection type. Comprehensions are particularly useful for transforming values, filtering data, extracting information, and constructing collections from existing sequences.

The goal is not to replace every loop with a comprehension. A good comprehension should make the logic easier to understand. When the transformation becomes complicated, a normal for loop is often the better choice.

What Is a Python Comprehension?

A comprehension creates a new collection by iterating over an existing iterable and optionally applying a condition. The general idea is:

[expression for item in iterable]

You can also add a filtering condition:

[expression for item in iterable if condition]

The expression determines what gets stored in the new collection, while the for clause determines which source values are processed.

Why Use Comprehensions?

Comprehensions can reduce repetitive code and keep simple transformations close to the collection being created. Compare a traditional loop with a list comprehension:

Traditional Loop

numbers = [1, 2, 3, 4, 5]

squares = []

for number in numbers:
    squares.append(number * number)

List Comprehension

numbers = [1, 2, 3, 4, 5]

squares = [number * number for number in numbers]

Both approaches produce the same result. The comprehension is shorter and can be easier to scan because the transformation and iteration are expressed together.

Python List Comprehensions

A list comprehension creates a new list. It is the most commonly used type of comprehension in Python and is useful for straightforward transformations and filtering operations.

numbers = [1, 2, 3, 4, 5]

squares = [number ** 2 for number in numbers]

print(squares)

The expression number ** 2 is executed for every element in the source list, and the resulting values are placed into a new list.

List Comprehension with Conditions

A condition can be added using if. In this form, only the elements that satisfy the condition are included in the resulting list.

numbers = range(1, 11)

even_numbers = [
    number
    for number in numbers
    if number % 2 == 0
]

print(even_numbers)

This pattern combines filtering and collection creation in one expression. It is useful for selecting records, filtering values, or preparing data for another operation.

Conditional Expressions in Comprehensions

There is an important distinction between a filtering if at the end of a comprehension and a conditional expression used inside the result expression.

A filtering condition decides whether an item should be included:

numbers = range(1, 6)

even_numbers = [
    number
    for number in numbers
    if number % 2 == 0
]

print(even_numbers)

A conditional expression changes the value that gets stored:

numbers = range(1, 6)

labels = [
    "even" if number % 2 == 0 else "odd"
    for number in numbers
]

print(labels)

These two patterns solve different problems. The first removes elements that do not satisfy the condition. The second keeps every element but chooses a different result for each one.

Transforming Strings with List Comprehensions

Comprehensions are useful for normalizing or transforming text collections. For example, a list of names can be converted into a consistent representation.

names = ["  Alice", "BOB", " Charlie  "]

clean_names = [
    name.strip().title()
    for name in names
]

print(clean_names)

This works well because each item follows the same simple transformation. When the transformation requires many conditions or multiple steps, a normal loop may communicate the logic better.

List Comprehension from a Range

The range() function is frequently combined with comprehensions for generating calculated values.

squares = [
    number * number
    for number in range(1, 11)
]

print(squares)

This pattern is useful for generating sequences, test data, transformed indexes, and calculated values without manually constructing the output list.

Python Set Comprehensions

A set comprehension follows the same general idea as a list comprehension but produces a set. Since sets contain unique values, duplicate results are automatically removed.

numbers = [1, 2, 2, 3, 4, 4, 5]

squares = {
    number * number
    for number in numbers
}

print(squares)

In this example, repeated input values can produce the same square, but the resulting set keeps each value only once.

Filtering with Set Comprehensions

Set comprehensions can also filter values. This is useful when you need a unique collection containing only values that satisfy a condition.

numbers = [1, 2, 3, 4, 5, 6, 6, 8]

even_squares = {
    number * number
    for number in numbers
    if number % 2 == 0
}

print(even_squares)

Use this pattern when both transformation and uniqueness are part of the requirement. If the original order or duplicate values must be preserved, a list comprehension is more appropriate.

Python Dictionary Comprehensions

A dictionary comprehension creates key-value pairs while iterating through an iterable. The basic syntax is:

{key_expression: value_expression for item in iterable}

For example, you can construct a dictionary mapping numbers to their squares.

numbers = range(1, 6)

squares = {
    number: number * number
    for number in numbers
}

print(squares)

Dictionary comprehensions are useful when both the key and value can be derived clearly from each source item.

Filtering Dictionary Comprehensions

Dictionary comprehensions can include conditions just like list and set comprehensions. This allows you to construct a dictionary containing only matching entries.

scores = {
    "Python": 92,
    "C#": 88,
    "Java": 79,
    "JavaScript": 95
}

high_scores = {
    language: score
    for language, score in scores.items()
    if score >= 90
}

print(high_scores)

This approach is useful for filtering configuration values, product data, metrics, API results, or any mapping where only certain entries should be retained.

Changing Dictionary Values

A dictionary comprehension can transform the values of an existing dictionary while preserving its keys.

prices = {
    "keyboard": 50,
    "mouse": 30,
    "monitor": 200
}

discounted = {
    product: price * 0.9
    for product, price in prices.items()
}

print(discounted)

The original dictionary remains unchanged because the comprehension creates a new dictionary.

Converting Between Collections

Comprehensions can be used when converting data from one collection representation into another. For example, a list of values can become a dictionary where each value is associated with derived metadata.

languages = ["Python", "C#", "Java"]

language_lengths = {
    language: len(language)
    for language in languages
}

print(language_lengths)

The resulting dictionary maps each language to the length of its name. This kind of transformation appears frequently in data preparation and reporting logic.

Nested Comprehensions

Comprehensions can contain multiple for clauses. This allows you to process nested iterables, but the resulting expression can become difficult to read quickly.

matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]

flattened = [
    value
    for row in matrix
    for value in row
]

print(flattened)

The first loop processes each row, and the second loop processes each value inside that row. The result is a single flattened list.

Nested comprehensions are appropriate when the structure remains easy to understand. For more complex nested logic, separate loops often produce more maintainable code.

Nested Loops vs Nested Comprehensions

Nested Loops

result = []

for row in matrix:
    for value in row:
        result.append(value)

Nested Comprehension

result = [
    value
    for row in matrix
    for value in row
]

Both are valid. The nested comprehension is compact, but the traditional loop may be easier for beginners or for transformations containing several operations.

Comprehensions with Multiple Conditions

Multiple boolean conditions can be used when filtering values. The conditions should remain simple enough that the final comprehension can still be understood without mentally reconstructing a large amount of control flow.

numbers = range(1, 21)

result = [
    number
    for number in numbers
    if number % 2 == 0
    and number % 3 == 0
]

print(result)

In this example, only values satisfying both conditions are included.

Using Functions Inside Comprehensions

A comprehension can call a function for each element. This can be useful when the transformation has already been given a clear name.

def normalize_name(name):
    return name.strip().title()

names = ["alice", " bob ", "CHARLIE"]

clean_names = [
    normalize_name(name)
    for name in names
]

print(clean_names)

Extracting complicated transformation logic into a function can keep the comprehension readable while still allowing code reuse and testing.

Comprehensions with Enumerate

Comprehensions can work with enumerate() when both the item and its position are useful.

languages = ["Python", "C#", "Java"]

indexed_languages = {
    index: language
    for index, language in enumerate(languages, start=1)
}

print(indexed_languages)

This produces a dictionary mapping numeric positions to language names. It is a useful example of combining Python's iteration utilities with comprehensions.

Comprehensions with Zip

The zip() function can combine related sequences before a comprehension transforms them.

languages = ["Python", "C#", "Java"]
scores = [92, 88, 81]

result = {
    language: score
    for language, score in zip(languages, scores)
}

print(result)

This is useful when related values are stored in separate sequences and need to be combined into a dictionary or another derived structure.

Choosing the Right Comprehension

Comprehension Produces Best Fit
List comprehension List Transformation while preserving sequence semantics
Set comprehension Set Transformation where unique results matter
Dictionary comprehension Dictionary Creating key-value mappings from data

Comprehensions and Readability

One of the most important Python comprehension rules is that shorter does not automatically mean better. A comprehension is valuable when its logic can be understood quickly.

Compare a simple transformation:

active_users = [
    user["name"]
    for user in users
    if user["active"]
]

This is easy to understand because there is one transformation and one filtering condition. A comprehension containing nested conditions, multiple function calls, deeply nested loops, and complicated expressions may be technically valid but harder to maintain.

Common Mistakes with Comprehensions

Making comprehensions too complex

A comprehension with too many operations can become harder to read than the loop it replaces. Readability should be the deciding factor.

Confusing filter and conditional expressions

An if at the end filters elements, while x if condition else y changes the value being produced.

Forgetting duplicate behavior

Set comprehensions remove duplicate results. Use a list comprehension when duplicate values or sequence semantics are important.

Accidentally creating the wrong collection

Square brackets create lists, curly braces without key-value pairs create sets, and curly braces with key-value expressions create dictionaries.

Ignoring side effects

Comprehensions are intended for creating collections. Using them primarily to trigger side effects such as printing or modifying unrelated state makes the code harder to understand.

Assuming comprehensions are always faster

Conciseness and performance are different concerns. Choose comprehensions primarily for clear collection construction, then measure performance when optimization actually matters.

Practical Example: Process User Records

Consider an application that receives user records and needs the names of active users. A list comprehension can express the transformation and filter directly.

users = [
    {"name": "Alice", "active": True},
    {"name": "Bob", "active": False},
    {"name": "Charlie", "active": True}
]

active_users = [
    user["name"]
    for user in users
    if user["active"]
]

print(active_users)

The result is a new list containing only the names of users whose active field is true. This is a common data-processing pattern in Python applications.

Practical Example: Build a Unique Collection

Suppose an application receives product tags with repeated values and needs a unique normalized set.

tags = [
    "Python",
    "python",
    "C#",
    "Python",
    "Angular"
]

normalized_tags = {
    tag.lower()
    for tag in tags
}

print(normalized_tags)

The set comprehension both transforms the text and ensures that duplicate normalized values are retained only once.

Practical Example: Transform Configuration Data

Dictionary comprehensions are useful when an application's configuration needs to be transformed into another mapping.

timeouts = {
    "database": 30,
    "api": 15,
    "cache": 10
}

milliseconds = {
    name: seconds * 1000
    for name, seconds in timeouts.items()
}

print(milliseconds)

Each key is preserved while its associated value is transformed. Because the operation is simple and consistent, a dictionary comprehension keeps the intent clear.

Best Practices for Python Comprehensions

  • Use comprehensions when they make simple collection transformations easier to read.
  • Keep the expression and conditions concise enough to understand at a glance.
  • Use list comprehensions for ordered list results, set comprehensions for unique results, and dictionary comprehensions for mappings.
  • Use functions to move complex transformation logic out of the comprehension.
  • Avoid using comprehensions only for side effects such as printing or mutating unrelated state.
  • Prefer a normal loop when multiple branches or complicated processing steps are required.
  • Remember that dictionary and set comprehensions have different output semantics from list comprehensions.
  • Prioritize readability over making code as short as possible.

Why Python Comprehensions Matter

Comprehensions are an important part of idiomatic Python because they provide a readable way to express common collection-building tasks. They can replace repetitive append, add, or assignment logic when the transformation is straightforward.

Understanding list, set, and dictionary comprehensions also improves your ability to read Python code written by other developers. You will frequently encounter comprehensions in application code, data-processing scripts, interview exercises, automation tools, and Python libraries.

The key skill is knowing when to use them. A good comprehension makes the relationship between input, transformation, and output obvious. A complicated comprehension does the opposite. Use the concise form when it improves clarity, and return to a normal loop when the logic deserves more room.

Code Examples

List Comprehension

python
numbers = range(1, 11)

squares = [
    number * number
    for number in numbers
]

print(squares)
    

List Comprehension with Filtering

python
numbers = range(1, 21)

even_numbers = [
    number
    for number in numbers
    if number % 2 == 0
]

print(even_numbers)
    

Set Comprehension

python
tags = [
    "Python",
    "python",
    "C#",
    "Python",
    "Angular"
]

normalized_tags = {
    tag.lower()
    for tag in tags
}

print(normalized_tags)
    

Dictionary Comprehension

python
scores = {
    "Python": 92,
    "C#": 88,
    "Java": 79,
    "JavaScript": 95
}

high_scores = {
    language: score
    for language, score in scores.items()
    if score >= 90
}

print(high_scores)
    

Nested Comprehension

python
matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]

flattened = [
    value
    for row in matrix
    for value in row
]

print(flattened)
    

Pro Tip

Use comprehensions for simple, readable collection transformations. When the logic starts feeling difficult to scan, switch to a normal loop instead of forcing everything into one expression.

More Python lessons

🎨 IgKnight Docs

Master HTML, CSS, JS, Python, .NET and more with easy-to-follow lessons and practical code examples.

© 2025 IgKnight Learning Platform. All rights reserved.