[Tutor] list comprehensions isolate variables but for loops don't - is there a special usage?

Jim Mooney cybervigilante at gmail.com
Wed Jun 5 07:53:18 CEST 2013


I just noticed that a list comprehension doesn't change a same-name
variable outside of it, but a for loop does. That is:

#Using Python 3.3.2 on Win 7

lst = [1,3,55,44,79,1,6,7,44,231,764,44,3,44]

frog = 'jumping'
print(frog, end=' ')
newlst = [frog**2 for frog in lst]
print(newlst, end=' ')
print(frog) # printed result is "jumping (the above list squared) jumping"

newlst = []
print(frog, end=' ')
for frog in lst:
    newlst.append(frog**2)
print(newlst,end=' ')
print(frog) # printed result is "jumping (the above list squared) 44"

For some reason it bothers me that a for loop can do this. Is there a
simple usage that isolates the for loop iteration variable the way a
list comprehension does? That is, without a lot of foofooraw. I can
isolate it by using a function but that's overkill for something
simple.

If my new autoheader wasn't noticed, I'm now on Py 3.3 for good. I
figure I learned what I should about the basic differences between 2.7
and 3.3, so it was time to move on. By the time I get done with the
two Lutz books and have a real use for the major libraries, most will
probably be ported. The Python 3 wall of superpowers already has
enough green to keep me busy for a long time (
http://python3wos.appspot.com  ;')

-- 
Jim
The insurance industry is America's largest organized criminal enterprise.


More information about the Tutor mailing list