0

On function call the following code prints 10, but don't know the reason can any body please explain

def test(x=[]):    
    x.append(10)
    print x
Aswin Murugesh
  • 10,831
  • 10
  • 40
  • 69
coderusher
  • 36
  • 4
  • because you are appending it – ɹɐqʞɐ zoɹǝɟ Feb 18 '14 at 17:12
  • 2
    Actually, it prints `[10]` on the first call, `[10, 10]` on the second call, `[10, 10, 10]` on the third call, etc. See [“Least Astonishment” in Python: The Mutable Default Argument](http://stackoverflow.com/q/1132941/395760). –  Feb 18 '14 at 17:13
  • what do you mean: prints 10 or test() returns 10? – halfbit Feb 18 '14 at 17:13

3 Answers3

2

This is called a default argument

>>> def test(x=[]):
...     x.append(10)
...     print x
... 
>>> test()
[10]
>>> test([20])
[20, 10]

You specify the value to be taken, if the argument is not passed during the function call. So, if a value is given as a parameter, that is used. Else, the default value is used.

Aswin Murugesh
  • 10,831
  • 10
  • 40
  • 69
2

it does not return 10 ... it simply prints it...

if you call it a second time it will print a list of 2 10's

a third time you will get a list with 3 10s

this is because a list is a mutable type and you are modifying the default argument with each call ... it does not start with a fresh list each call

Im not sure if this answers your question ...

Joran Beasley
  • 110,522
  • 12
  • 160
  • 179
0
def test(x=[]):

Here you are defining a function test which takes a parameter called x. x is defined to take a default argument of [], that is an empty list.

  x.append(10)

Here you append 10 to the empty list, which becomes [ 10 ], that is a list which contains the number 10.

  print x

Here you print the list. That is why when you call test() you get

>>> test()
[10]

The default argument is only evaluated once; the same value is passed to every call to test() in which you do not specify an argument explicitly.

So if you call test() again you get:

>>> test()
[10, 10]

As you can see another 10 is appended to the original list.

Nicola Musatti
  • 17,834
  • 2
  • 46
  • 55