Incorrect scope of list comprehension variables
Brian Blais
bblais at bryant.edu
Sun Apr 4 09:22:37 EDT 2010
On Apr 4, 2010, at 3:17 , Stephen Hansen wrote:
> Where exactly does this common sense come from? A list
> comprehension is
> basically syntactic sugar over a for loop, and...
well, since I've been bitten by this particular wart, I was surprised
to see that the list comp didn't have it's own scope. If it's
syntactic sugar for a for-loop, I figured that rather than converting
d = dict()
for r in [1,2,3]:
d[r] = [r for r in [4,5,6]]
to
d = dict()
for r in [1,2,3]:
L=[]
for r in [4,5,6]:
L.append(r)
d[r] = L
it would convert it to something like:
d = dict()
for r in [1,2,3]:
L=[]
for _r in [4,5,6]:
L.append(_r)
d[r] = L
still a for-loop, but without the surprising side-effect. I'm glad
they fixed this one!
surely, once you know, it's easy to overcome. as a curiosity, I just
went and skimmed the section:
http://docs.python.org/tutorial/datastructures.html
which describes list comps, and didn't see any mention of this
behavior. it's probably there, but it certainly doesn't jump out.
bb
--
Brian Blais
bblais at bryant.edu
http://web.bryant.edu/~bblais
http://bblais.blogspot.com/
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20100404/7008e389/attachment-0001.html>
More information about the Python-list
mailing list