Lesson 16: Comprehensions in Python

๐ŸŽฏ 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']


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *