Why does Python's 'for ... in' work differently on a list of values vs. a list of dictionaries?
Posted
by Code Duck
on Stack Overflow
See other posts from Stack Overflow
or by Code Duck
Published on 2010-05-28T04:03:52Z
Indexed on
2010/05/28
4:11 UTC
Read the original article
Hit count: 205
I'm wondering about some details of how for ... in works in Python.
My understanding is for var in iterable
on each iteration creates a variable, var, bound to the current value of iterable. So, if you do for c in cows; c = cows[whatever]
, but changing c within the loop does not affect the original value. However, it seems to work differently if you're assigning a value to a dictionary key.
cows=[0,1,2,3,4,5]
for c in cows:
c+=2
#cows is now the same - [0,1,2,3,4,5]
cows=[{'cow':0},{'cow':1},{'cow':2},{'cow':3},{'cow':4},{'cow':5}]
for c in cows:
c['cow']+=2
# cows is now [{'cow': 2}, {'cow': 3}, {'cow': 4}, {'cow': 5}, {'cow': 6}, {'cow': 7}
#so, it's changed the original, unlike the previous example
I see one can use enumerate to make the first example work, too, but that's a different story, I guess.
cows=[0,1,2,3,4,5]
for i,c in enumerate(cows):
cows[i]+=1
# cows is now [1, 2, 3, 4, 5, 6]
Why does it affect the original list values in the second example but not the first?
© Stack Overflow or respective owner