So far, we’ve covered Lists, Tuples, Sets, and Dictionaries. Now let’s learn a powerful Python feature that helps you write cleaner and more efficient code.
📖 Phase 1: Programming Fundamentals
📌 Topic 19: List & Dictionary Comprehensions
Comprehensions provide a short and readable way to create lists and dictionaries using loops and conditions.
🔹 1. List Comprehension
Normally, you might write:
numbers = []
for i in range(1, 6):
numbers.append(i)
print(numbers)
Output:
[1, 2, 3, 4, 5]
With list comprehension:
numbers = [i for i in range(1, 6)]
Much shorter.
Basic Syntax:
[expression for item in iterable]
Example:
squares = [x * x for x in range(1, 6)]
Output:
[1, 4, 9, 16, 25]
🔹 2. List Comprehension with Conditions
You can add an if condition:
even_numbers = [
x for x in range(1, 11)
if x % 2 == 0
]
Output:
[2, 4, 6, 8, 10]
General syntax:
[expression for item in iterable if condition]
🔹 3. Converting Values
Comprehensions aren't only for numbers.
names = ["alex", "sam", "john"]
uppercase = [name.upper() for name in names]
Output:
['ALEX', 'SAM', 'JOHN']
🔹 4. Using if-else
When using if-else, the syntax changes:
result = [
"Even" if x % 2 == 0 else "Odd"
for x in range(1, 6)
]
Output:
['Odd', 'Even', 'Odd', 'Even', 'Odd']
Remember:
# Only if
[expression for x in data if condition]
# if-else
[expression_if_true if condition else expression_if_false for x in data]
This is a common interview question.
🔹 5. Nested List Comprehension
Traditional approach:
result = []
for x in [1, 2]:
for y in [10, 20]:
result.append((x, y))
List comprehension:
result = [
(x, y)
for x in [1, 2]
for y in [10, 20]
]
Output:
[(1, 10), (1, 20), (2, 10), (2, 20)]
🔹 6. Dictionary Comprehension
Basic syntax:
{key: value for item in iterable}
Example:
squares = {
x: x * x
for x in range(1, 6)
}
Output:
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
🔹 7. Dictionary Comprehension with Conditions
even_squares = {
x: x * x
for x in range(1, 11)
if x % 2 == 0
}
Output:
{2: 4, 4: 16, 6: 36, 8: 64, 10: 100}
🔹 8. Creating a Dictionary from Two Lists
names = ["Alex", "Sam", "John"]
scores = [85, 90, 78]
result = {
name: score
for name, score in zip(names, scores)
}
Output:
{'Alex': 85, 'Sam': 90, 'John': 78}
🔹 9. Transforming an Existing Dictionary
prices = {
"Laptop": 800,
"Phone": 500,
"Tablet": 300
}
updated_prices = {
item: price * 1.10
for item, price in prices.items()
}
🔹 10. Filtering a Dictionary
expensive = {
item: price
for item, price in prices.items()
if price > 500
}
Output:
{'Laptop': 800}