Python 24-Day Course - Day 7: Comprehensions

Day 7: Comprehensions

List Comprehension

Condense a loop into a single line to create a list.

# Traditional approach
squares = []
for x in range(10):
    squares.append(x ** 2)

# Comprehension
squares = [x ** 2 for x in range(10)]
print(squares)  # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

Conditional Filtering

# Filter even numbers only
evens = [x for x in range(20) if x % 2 == 0]
print(evens)  # [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]

# if-else expression
labels = ["even" if x % 2 == 0 else "odd" for x in range(5)]
print(labels)  # ['even', 'odd', 'even', 'odd', 'even']

Dictionary Comprehension

names = ["Alice", "Bob", "Charlie"]
name_lengths = {name: len(name) for name in names}
print(name_lengths)  # {'Alice': 5, 'Bob': 3, 'Charlie': 7}

# Dictionary filtering
scores = {"Math": 90, "English": 65, "Science": 88, "Korean": 72}
passed = {k: v for k, v in scores.items() if v >= 80}
print(passed)  # {'Math': 90, 'Science': 88}

Set Comprehension

sentence = "hello world"
unique_chars = {ch for ch in sentence if ch != " "}
print(unique_chars)  # {'h', 'e', 'l', 'o', 'w', 'r', 'd'}

Nested Comprehension

matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flat = [num for row in matrix for num in row]
print(flat)  # [1, 2, 3, 4, 5, 6, 7, 8, 9]

Today’s Exercises

  1. Use a comprehension to extract only the common multiples of 3 and 5 from 1 to 100.
  2. From a list of strings, create a list containing only words with a length of 5 or more, converted to uppercase.
  3. Write a comprehension that swaps the keys and values of a dictionary.

Was this article helpful?