0

Possible Duplicate:
“Least Astonishment” in Python: The Mutable Default Argument

def test(mylist=['a']):  
        mylist.append(1.)  
        print mylist

test()  
test()

Is giving me the following result:

['a', 1.0]  
['a', 1.0, 1.0]

Why is this the case? I would expect:

['a', 1.0]  
['a', 1.0]  

The test is called two times and eachtime mylist is created as a local variable.

Community
  • 1
  • 1
user1514974
  • 21
  • 1
  • 3
  • 4
    See ["Least Astonishment" in Python: The Mutable Default Argument](http://stackoverflow.com/q/1132941) – Martijn Pieters Jul 10 '12 at 14:21
  • 1
    The list is only created once at the function definition :) Never use a mutable datatype as default argument. – schlamar Jul 10 '12 at 14:23
  • 1
    @ms4py -- never, unless you're intentionally using it as a cache across calls. A default argument of {} can be used for quick-and-dirty memoization, for instance. – Russell Borogove Jul 10 '12 at 18:13

0 Answers0