Generator Comprehensions

pirx at mail.com pirx at mail.com
Tue Jan 29 15:58:06 EST 2002


1. I didn't know that list comprehensions can change local vars either

2. the reason it bothers me: list comprehensions are _functional_ construct,
so they should be side-effect free (unless somebody deliberately calls
inside them functions which aren't).

3. I suspect it is no big deal for most programmers - but it is not elegant,
so long term danger for Python-the-language


"Skip Montanaro" <skip at pobox.com> wrote in message
news:mailman.1012318487.21582.python-list at python.org...
>
>     >> I don't see any spurious locals:
>     >>
>     >> >>> def f(n):
>     >> ...   l = [i for i in range(n)]
>     >> ...   print locals()
>     >> ...   return l
>     >> ...
>     >> >>> f(5)
>     >> {'i': 4, 'l': [0, 1, 2, 3, 4], 'n': 5}
>     >> [0, 1, 2, 3, 4]
>
>     hamish> I think the original author was referring to the very fact
that
>     hamish> 'i' is among the locals that you printed out.
>
> Ah, well in that case, I can fall back on the excuse that "list
> comprehensions are essentially syntactic sugar sprinkled on for loops".
;-)
>
> If you convert a list comprehension to its equivalent series of for loops,
> if statements, and list appends, you wind up at the end with a loop index
> variable that is not destroyed.  For example, the above is equivalent to
>
>     l = []
>     for i in range(n):
>         l.append(i)
>
> "i" doesn't go away after the for loop.  Nor does it after the list
> comprehension.
>
> --
> Skip Montanaro (skip at pobox.com - http://www.mojam.com/)
>





More information about the Python-list mailing list