Help - strange behaviour from python list

Schüle Daniel uval at rz.uni-karlsruhe.de
Tue Apr 11 08:08:51 EDT 2006


Sean Hammond schrieb:
> 
> I've managed to create a scenario in which editing an object in a list 
> of objects seems to edit every object in the list, rather than just the 
> one. I'm totally stumped and wondered if anyone would be kind enough to 
> read my explanation and see if they have any suggestions. I have 
> probably stumbled into some typical newbie problem, but anyway:
> 

just a hint

 >>> def foo(val,lst=[]):
...     lst.append(val)
...     print lst
...
 >>>
 >>>
 >>> foo(1)
[1]
 >>> foo(2)
[1, 2]
 >>> foo(3)
[1, 2, 3]
 >>> foo(4,[0])
[0, 4]
 >>>

here list lst is created and bound once


compare with this one (which is what you really want)

 >>> def bar(val, lst=None):
...     if lst is None:
...             lst = []
...     lst.append(val)
...     print lst
...
 >>> bar(1)
[1]
 >>> bar(2)
[2]
 >>> bar(3, [0])
[0, 3]
 >>>

hth, Daniel



More information about the Python-list mailing list