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 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 such an operation as we did in one of the previous examples of this chapter:
chapter02_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]