4.5 Comprehensions

4.5 Comprehensions

Learning the elegant and "Pythonic" syntax of comprehensions for creating lists, sets, and dictionaries in a concise and efficient way.

Comprehensions are one of the most elegant and efficient ways to create lists, sets, and dictionaries from other sequences, often in a single line of code. They are a characteristic example of Python's philosophy of writing readable and concise code.

List Comprehension

This is the most common form. It allows you to create a new list by applying an expression to each item of an existing sequence, with optional filtering. The syntax is: `[expression for item in iterable if condition]`.
# Traditional way
squares_traditional = []
for x in range(1, 6):
    squares_traditional.append(x**2)

# List Comprehension way
squares = [x**2 for x in range(1, 6)]
print(f"Squares: {squares}")

# Filtering for even numbers
numbers = [1, 2, 3, 4, 5, 6]
evens = [num for num in numbers if num % 2 == 0]
print(f"Evens: {evens}")

Dictionary Comprehension

Similar to lists, you can create dictionaries concisely. The syntax is: `{key: value for item in iterable if condition}`.
# Creating a dictionary with numbers and their squares
squares_dict = {x: x**2 for x in range(1, 6)}
print(f"Dictionary of squares: {squares_dict}")

# Creating a dictionary from a list, with filtering
names = ["Anna", "Nikos", "Eleni"]
name_lengths_dict = {name: len(name) for name in names if len(name) > 4}
print(f"Dictionary of names with length > 4: {name_lengths_dict}")

Set Comprehension

The syntax is similar to that of a dictionary, but without the key: `{expression for item in iterable if condition}`.
# Creating a set with squares of even numbers
numbers_set = [1, 2, 3, 4, 5, 6, 2, 4] # list with duplicates
even_squares_set = {x**2 for x in numbers_set if x % 2 == 0}
print(f"Set of squares of even numbers (unique values): {even_squares_set}")

Practical Exercises

Explore More with AI

Use AI to generate new examples, delve deeper into theory, or get your questions answered.