Weird lambda rebinding/reassignment without me doing it
A.T.Hofkamp
hat at se-162.se.wtb.tue.nl
Thu Jul 10 10:10:32 EDT 2008
Python doesn't use value semantics for variables but reference semantics:
a = [1]
b = a
In many languages, you'd now have 2 lists. In Python you still have one list,
and both a and b refer to it.
Now if you modify the data (the list), both variables will change
a.append(2) # in-place modification of the list
print b # will print [1,2]
If you don't want this, you should make a copy somewhere
a = a + [2]
or
b = a[:]
It takes a bit of getting used to, but it is very handy in practice.
Read the docs about 'immutable' and 'mutable' types.
(I expected this to be a FAQ, but I couldn't quickly find a matching entry)
Albert
More information about the Python-list
mailing list