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.
| Method | Syntax | Description |
|---|---|---|
| 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.
| Method | Syntax | Description |
|---|---|---|
| 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.
Python Comprehensions
Write cleaner, faster Python. Master list, dictionary, and set comprehensions with practical examples, filtering conditions, and nested loops.
How to Sort a List in Python
Learn how to sort a list in Python using the sort() method and the sorted() function. Discover custom key sorting and reverse order examples.
Python vs JavaScript: Which Programming Language is Best?
A comprehensive comparison between Python and JavaScript. Explore syntax differences, performance, use cases (backend vs frontend), and coding examples.