[Tutor] How to use function with default values ?

cs at zip.com.au cs at zip.com.au
Sun Aug 7 20:16:05 EDT 2016


On 07Aug2016 09:19, Alan Gauld <alan.gauld at yahoo.co.uk> wrote:
>On 07/08/16 04:22, rishabh mittal wrote:
>> I am new to python and come from C language background. I couldn't able to
>> understand this
>>  >>> def f(a, L=[]):
>> ...     L.append(a)
>> ...     return L
>>>>> print(f(1))
>> [1]
>>>>> print(f(2))
>> [1, 2]
[...]
>> In the first example if i call function f then it looks like L is treated
>> as a static object which is not reinitialized in the subsequent function
>> calls.
>
>That's more or less correct. The default object is created at definition
>time and that same object is used for any invocation of the function
>that does not provide an explicit value.

Just a further addition to Alan's explaination: because the default values are 
defined at the same time that the function is defined, the common idom in 
Python for default values looks like this:

  def f(a, L=None):
      if L is None:
          L = []
      ...

Which binds L to a new list every time the function is called (if L is not 
presupplied).

The "None" is not particularly special; like the number 10 it is immutable, so 
defining it the once at function definition time is not an issue. It is simply 
an immutable sentinel value representing "not a normal valid value", and the 
common choice in Python.

Cheers,
Cameron Simpson <cs at zip.com.au>


More information about the Tutor mailing list