Python Comprehensions Cheat Sheet

Write concise and readable list, dictionary, set, and generator comprehensions in Python.

List and Set Comprehensions

Creating sequences and sets inline using syntactic sugar loops.

MethodSyntaxDescription
List Comprehension[x * 2 for x in my_list]Constructs a new list by applying expressions on elements of an iterable.
Conditional List[x for x in my_list if x > 0]Applies a filter predicate, only keeping elements that satisfy the condition.
Nested Loops[x + y for x in list1 for y in list2]Flattens nested operations. Runs inner loops for each outer loop iteration.
Set Comprehension{x for x in my_list}Generates a set, applying deduplication automatically.

Dictionary and Generator Comprehensions

Generating mappings and lazy-evaluation streams inline.

MethodSyntaxDescription
Dict Comprehension{k: v for k, v in pairs}Constructs a dictionary inline.
Conditional Dict{k: v for k, v in pairs if k is not None}Constructs a dictionary while ignoring unwanted values.
Generator Expression(x ** 2 for x in range(10))Returns a lazy generator iterator object. Evaluates items one at a time to conserve memory.

Frequently Asked Questions

When should I avoid using list comprehensions?

Avoid list comprehensions if they are overly complex or have multiple nested loops, as this reduces code readability.

What is the difference between a list comprehension and a generator expression?

List comprehensions evaluate immediately and construct the list in memory, whereas generator expressions yield items lazily on-demand, saving memory.

Keep Learning

Recommended Python Resources

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