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
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
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.
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 ...
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.