0

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

I have written the following python program:

#!/usr/bin/env python

def bug( numbers = [] ):
    numbers.append( 1 )
    return numbers

print bug()
print bug()

The result i would expect is

[1]
[1]

But i got

[1]
[1, 1]

Is this a bug?

Community
  • 1
  • 1

2 Answers2

0

No, this is not a bug and this behaviour has been around in Python for a very long time.

The problem is that the list object is mutable, i.e. you can change it, and when you call a function you don't get a new default value. What's happening is this:

def bug( numbers = [] ):
   numbers.append( 1 )
   return numbers

At this point the function bug has been created and the list that is default value for numbers created.

print bug()

Now we've called bug once and added 1 to the list that was created when the function was defined.

print bug()

When we call the function again we get the same list as before so we get two 1s added to the list.

The usual solution is to define your function as follows:

def bug(numbers = None):
    if numbers is None:
        numbers = []
    numbers.append(1)
    return numbers

Read this for more details.

Andrew Wilkinson
  • 10,682
  • 3
  • 35
  • 38
0

numbers=[] is evaluated only once (when the function is defined). So it's always the same list.

To avoid this, change the function like this:

def not_a_bug(numbers=None):
    if numbers is None:
        numbers = []
    numbers.append(1)
    return numbers
ThiefMaster
  • 310,957
  • 84
  • 592
  • 636