Expert Python Programming(Third Edition)
上QQ阅读APP看书,第一时间看更新

Generator expressions

Generator expressions are another syntax element that allows you to write code in a more functional way. Its syntax is similar to comprehensions that are used with dict, set, and list literals. A generator expression is denoted with parentheses, like in the following example:

(item for item in iterable_expression)

Generator expressions can be used as input arguments in any function that accepts iterators. They also allow if clauses to filter specific elements. This means that you can often replace complex map() and filter() constructions with more readable and compact generator expressions. Consider one of the previous complex map()/filter() examples compared with the equivalent generator expression:

sequence = filter(
lambda square: square % 3 == 0 and square % 2 == 1,
map(
lambda number: number ** 2,
count()
)
)

sequence = (
square for square
in (number ** 2 for number in count())
if square % 3 == 0 and square % 2 == 1
)

Let's discuss function and variable annotations in the next section.