Syntax
[expression for item in iterable if condition]
Example:
nums = [1, 2, 3, 4, 5]
squares = [n**2 for n in nums]
print(squares) # [1, 4, 9, 16, 25]
Syntax
{key_expression: value_expression for item in iterable if condition}
Example:
nums = [1, 2, 3, 4, 5]
square_map = {n: n**2 for n in nums}
print(square_map) # {1:1, 2: 4, 3: 9, 4: 16, 5: 25}
Feature | List comprehension | Dict Comprehension |
---|---|---|
Output Type | List([] ) | Dictionary([] ) |
Elements Produced | Single values | Key:Value pairs |
Syntax | [expr for item in iterable] | {key: value for item in iterable} |
Use Cases | Transform sequence into list | Map relationships (key → value) |
List comprehension with condition:
evens= [n for n in range(10) if n % 2 == 0]
print(evens) # [0, 2, 4, 6, 8]
Dict comprehension with condition:
even_map = {n: n**2 for n in range(10) if n % 2 == 0}
print(even_map) # {0: 0, 2: 4, 4: 16, 6: 36, 8: 64}
1. List Comprehension → Flatten Matrix
matrix = [[1, 2], [3, 4], [5, 6]]
flatten = [num for row in matrix for num in row]]
print(flatten) # [1, 2, 3, 4, 5, 6]
2. Dict Comprehension → Word Count
sentence = "python interview preparation with python"
word_count = {word: sentence.split().count(word) for word in set(sentence.split())}
print(word_count)
# {'preparation': 1, 'python': 2, 'with': 1, 'interview': 1}
3. Filter Dictionary
prices = {"apple": 50, "banana": 20, "mango": 60}
expensive = {k: v for k, v in prices.items() if v > 30}
print(expensive) # {'apple': 50, 'mango': 60}
A list comprehension produces a list using a singe expression, while a dict comprehension produces a dictionary with key-value pairs.
The syntax differs slightly:
[expr for item in iterable if condition]
"{key: value for item in iterable if condition}
"List comprehensions are best for transforming sequences, while dict comprehensions are ideal for mapping relationships or filtering dictionaries. Both are faster and more Pythonic than using loops.
Leave a Reply