unintuitive for-loop behavior
Jussi Piitulainen
jussi.piitulainen at helsinki.fi
Sat Oct 1 09:32:46 EDT 2016
Rustom Mody writes:
> And then define comprehensions not as now done in terms of for loops
> that mutatingly extend the list being built up but as recursive
> functions that get (re)called for every new value of the comprehension
> variable passed and therefore fresh-bound as parameter
You'd get the magical semantics for comprehensions from the current
definition of comprehension semantics in terms of the loop, if the loop
semantics was magical. Let me demonstrate. (The b-word is unfortunately
not available, so I substitute "magical" instead.)
# delayd = [ lambda : c for c in "abracadabra" ]
# is roughly/almost equal to the following.
delayd = []
for c in "abracadabra":
delayd.append(lambda : c)
print('Python:', ''.join(f() for f in delayd))
# But that for-loop could have been roughly equal to the following,
# giving both the comprehension and the underlying for-loop a
# semantics that some people say they would prefer.
delayd = [] # reset the list, not part of the loop
g1 = iter("abracadabra")
try:
while True:
def g2(c):
delayd.append(lambda : c)
g2(next(g1))
except StopIteration:
pass
print('Magick:', ''.join(f() for f in delayd))
# Output from the above:
# Python: aaaaaaaaaaa
# Magick: abracadabra
More information about the Python-list
mailing list