PEP 572: Change toy example to not be a simple pair

This commit is contained in:
Chris Angelico 2018-03-01 01:06:52 +11:00
parent 5e8b724506
commit 2cd3526738
1 changed files with 9 additions and 6 deletions

View File

@ -52,26 +52,29 @@ Example usage
These list comprehensions are all approximately equivalent::
# Calling the function twice
stuff = [[f(x), f(x)] for x in range(5)]
stuff = [[f(x), x/f(x)] for x in range(5)]
# External helper function
def pair(value): return [value, value]
def pair(value): return [value, x/value]
stuff = [pair(f(x)) for x in range(5)]
# Inline helper function
stuff = [(lambda y: [y,y])(f(x)) for x in range(5)]
stuff = [(lambda y: [y,x/y])(f(x)) for x in range(5)]
# Extra 'for' loop - see also Serhiy's optimization
stuff = [[y, y] for x in range(5) for y in [f(x)]]
stuff = [[y, x/y] for x in range(5) for y in [f(x)]]
# Iterating over a genexp (similar to the above but reordered)
stuff = [[y, x/y] for y in (f(x) for x in range(5))]
# Expanding the comprehension into a loop
stuff = []
for x in range(5):
y = f(x)
stuff.append([y, y])
stuff.append([y, x/y])
# Using a statement-local name
stuff = [[(f(x) as y), y] for x in range(5)]
stuff = [[(f(x) as y), x/y] for x in range(5)]
If calling ``f(x)`` is expensive or has side effects, the clean operation of
the list comprehension gets muddled. Using a short-duration name binding