> > A trivial example is: > > Are there non-trivial examples? The PEP suggests that they exist, but > doesn't provide any. > > > iterators = [] > > for i in range(5): > > iterators.append(x*2 for x in range(i)) > > > > print map(list,iterators) > > > > If a listcomp is used, you get: > > > > [[],[0,],[0,2],[0,2,4],[0,2,4,6],[0,2,4,6,8]] > > > > If genexprs do late binding, you get: > > > > [[0,2,4,6,8],[0,2,4,6,8],[0,2,4,6,8],[0,2,4,6,8],[0,2,4,6,8]] > > Note that Armin Rigo suggested a small change here a few weeks ago that > makes the list comp and the gen expr behave the same way. I may be mistaken, but I had always assumed it should be the way Armin suggested. > The range(i) part of the gen expr is evaluated at the point of > definition. The gen expr, thus, translates to: > > def f(it): > for x in it: > yield x * 2 > > iterators.append(f(range(i)) > > As a result of this change, the only new scope is for the body of the > target expression. I don't know how that effects the earlier examples. There were definitely examples along the lines of using 'i' in the target expression. > BTW is there good terminology for describing the parts of a list comp or > gen expr? How about the iterator, the conditions, and the expression? Expression is too generic; I suggest target expression. --Guido van Rossum (home page: http://www.python.org/~guido/)
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4