๐ฏ Lesson Objective
To learn how to create lists, dictionaries, and sets efficiently using comprehensions, making Python code more concise and readable.
๐งฉ 1. What Is a Comprehension?
A comprehension is a compact way to create collections (list, dict, set) in a single line using a for loop and optional condition.
โ๏ธ 2. List Comprehension
Syntax:
[expression for item in iterable if condition]
โ Example 1: Squares of Numbers
squares = [x**2 for x in range(1, 6)]
print(squares)
Output:
[1, 4, 9, 16, 25]
โ Example 2: Even Numbers Only
evens = [x for x in range(10) if x % 2 == 0]
print(evens)
Output:
[0, 2, 4, 6, 8]
๐ 3. Dictionary Comprehension
Syntax:
{key_expression: value_expression for item in iterable if condition}
โ Example 1: Square Dictionary
squares_dict = {x: x**2 for x in range(1, 6)}
print(squares_dict)
Output:
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
โ Example 2: Filter Odd Numbers
odd_dict = {x: x**3 for x in range(10) if x % 2 != 0}
print(odd_dict)
Output:
{1: 1, 3: 27, 5: 125, 7: 343, 9: 729}
๐งฑ 4. Set Comprehension
Syntax:
{expression for item in iterable if condition}
โ Example: Unique Squares
nums = [1, 2, 2, 3, 4, 4, 5]
unique_squares = {x**2 for x in nums}
print(unique_squares)
Output:
{1, 4, 9, 16, 25}
๐ ๏ธ 5. Nested Comprehension
โ Example: Multiplication Table
table = [[i*j for j in range(1, 6)] for i in range(1, 6)]
for row in table:
print(row)
Output:
[1, 2, 3, 4, 5]
[2, 4, 6, 8, 10]
[3, 6, 9, 12, 15]
[4, 8, 12, 16, 20]
[5, 10, 15, 20, 25]
๐ 6. Conditional Expressions in Comprehension
โ Example: Label Numbers
labels = ["Even" if x % 2 == 0 else "Odd" for x in range(1, 11)]
print(labels)
Output:
['Odd', 'Even', 'Odd', 'Even', 'Odd', 'Even', 'Odd', 'Even', 'Odd', 'Even']
๐ 7. Real-Life Example โ Filtering Names
names = ["Ali", "Sara", "John", "Lily", "Bob"]
short_names = [name for name in names if len(name) <= 3]
print(short_names)
Output:
['Ali', 'Bob']

Leave a Reply