List and Dict Comprehensions
Learn list and dict Comprehensions
List & Dict Comprehensions
Comprehensions are one of the most loved Python features — they let you build lists and dictionaries in a single concise line, replacing what would otherwise be a multi-line loop.
List Comprehensions
The basic idea: instead of building a list with a loop and append, you describe the list directly.
Without comprehension:
With comprehension:
The general syntax is:
Filtering with a Condition
You can add an if clause to keep only elements that satisfy a condition:
Transforming Strings
Comprehensions work on any iterable, including strings and lists of strings:
Reading Input into a List
This is probably the most used comprehension in competitive programming:
Nested Comprehensions — 2D Structures
You can nest comprehensions to build 2D lists. The outer loop comes first:
Output:
Flattening a 2D List
The order here is: outer loop first (for row in matrix), inner loop second (for x in row) — same as the equivalent nested for loops written top to bottom.
if-else Inside a Comprehension
You can also use a ternary expression to transform each element conditionally. Note the position — if/else for transformation goes before the for, while if for filtering goes after:
Dict Comprehensions
Dict comprehensions build dictionaries the same way:
Filtering in Dict Comprehensions
Inverting a Dictionary
Swap keys and values — useful when you need reverse lookups:
Building a Frequency Dict
Note: this is O(n^2) because a.count(x) scans the whole list for each unique element. For large inputs use Counter instead.
Coordinate Compression in One Line
Set Comprehensions
While we're here — set comprehensions work the same way, just with curly braces and no key-value pair:
When Not to Use Comprehensions
Comprehensions shine for simple, readable transformations. Avoid them when:
- The logic requires multiple statements