From 2cd352673896e84c4d30f22d0829fae65e253e85 Mon Sep 17 00:00:00 2001 From: Chris Angelico Date: Thu, 1 Mar 2018 01:06:52 +1100 Subject: [PATCH] PEP 572: Change toy example to not be a simple pair --- pep-0572.rst | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/pep-0572.rst b/pep-0572.rst index 0e08acebb..e44d27b8f 100644 --- a/pep-0572.rst +++ b/pep-0572.rst @@ -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