Comprehensions
List Comprehensions — The Pythonic Shortcut
A list comprehension is like a factory assembly line: raw materials go in one end, get transformed, and finished products come out the other end — all in one smooth operation.
Instead of writing a loop, creating an empty list, and appending items one by one, you describe the entire thing in a single line: [expression for item in iterable].
The basic pattern is: [what_you_want for each_item in some_collection]
List Comprehensions vs. Loops
Filtering with Conditions
You can add an if clause at the end to filter which items make it through the assembly line. Only items where the condition is True get included in the result.
Pattern: [expression for item in iterable if condition]
You can even use if/else in the expression part (before for) to transform items differently based on a condition.
Filtering & Conditional Expressions
Dict & Set Comprehensions
The same idea works for dictionaries and sets! Just change the brackets:
- Dict comprehension:
{key: value for item in iterable}— uses curly braces with a colon. - Set comprehension:
{expression for item in iterable}— curly braces, no colon.
Dict & Set Comprehensions
Generator Expressions — The Lazy Cousin
A generator expression looks like a list comprehension but uses () instead of []. It doesn't build the whole list in memory — it produces items one at a time, on demand. This is perfect for huge datasets where you'd run out of memory building a full list.
Generator Expressions
if/for clauses, switch to a regular loop. Readability beats cleverness every time.