Categories

Chapter 4.3: Comprehensions

Understanding comprehensions

Python provides a unique and powerful feature called comprehensions, which allow us to construct new lists, dictionaries, and sets in a concise and readable way.

List Comprehensions

A list comprehension provides a way to create a new list by applying an expression to each item in an existing list (or other iterable), optionally filtering items. Here is the basic syntax:

new_list = [expression for item in iterable if condition]

Let’s see an example where we create a list of squares for numbers from 0 to 9:

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

We can add a condition to filter items. For instance, let’s create a list of squares for only the even numbers from 0 to 9:

even_squares = [x**2 for x in range(10) if x % 2 == 0]
print(even_squares)  # prints: [0, 4, 16, 36, 64]

Dictionary Comprehensions

Like list comprehensions, dictionary comprehensions allow us to create dictionaries in a concise way. The syntax is:

new_dict = {key_expression: value_expression for item in iterable if condition}

Here is an example where we create a dictionary that maps numbers from 0 to 4 to their squares:

square_dict = {x: x**2 for x in range(5)}
print(square_dict)  # prints: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

Set Comprehensions

Set comprehensions are similar to list and dictionary comprehensions but produce a set, which means the results are unordered and contain no duplicates:

new_set = {expression for item in iterable if condition}

For example, we can create a set of the remainders when dividing numbers from 0 to 9 by 4:

remainders = {x % 4 for x in range(10)}
print(remainders)  # prints: {0, 1, 2, 3}

Comprehensions are a powerful feature of Python, providing a way to transform and filter data in a readable and efficient manner. Understanding them is key to writing idiomatic Python code.

Leave a Reply

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