Comprehensions and Assignment Expressions
Explore how to write idiomatic Python code by using comprehension expressions and assignment expressions. This lesson helps you understand when to prefer comprehensions for clarity and efficiency, how assignment expressions introduced in Python 3.8 can simplify your code, and the balance between code compactness and readability. By the end, you will be able to write more maintainable and performant Python code using these techniques.
Comprehension expressions are usually a more concise way of writing code, and in general, code written this way tends to be easier to read. If we need to do some transformations on the data we're collecting, using a comprehension might lead to more complicated code. In these cases, writing a simple for loop should be preferred instead.
There is, however, one last resort we could apply to try to salvage the situation: assignment expressions. In this lesson, we discuss these alternatives.
Usage of comprehension expressions
The use of comprehensions is recommended for creating data structures in a single instruction, instead of multiple operations. For example, if we wanted to create a list with calculations over some numbers in it, we might try writing it like this:
numbers = []for i in range(10):numbers.append(run_calculation(i))
Instead, we could create the list directly:
numbers = [run_calculation(i) for i in range(10)]