Operating over sequences – list comprehensions and generators
In this section, we'll cover what are probably the most idiomatic constructions in Python: list comprehensions and generators. You'll see that they are very useful for reading and transforming sequences of data with very minimal syntax.
List comprehensions
In programming, a very common task is to transform a sequence (let's say a list) into another, for example, to filter out or transform elements. Usually, you would write an operation as we did in one of the previous examples of this chapter:
chapter2_basics_02.py
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] even = [] for number in numbers: if number % 2 == 0: even.append(number) print(even) # [2, 4, 6, 8, 10]
With this approach...