0
votes

As I'm new to python I've started the topic of default arguments As per that of the definition I've understood that the default arguments are evaluated only once and that at the point of function definition but this code fragment created the confusion

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

In the above code L being a variable Modified to list on the first function call ex.f(1) But even for the second time when the function is called L is being modified to list ex.. f(1) f(2) Results in [1] [2] Could you'll actually be precise in explaining how the above code evaluation is done

2

2 Answers

1
votes

Everytime you call f without a 2nd parameter, a new list is created. If you want to reuse the list, you need to store the result of f

new_list = f(1)
f(2, new_list)
print(new_list)

Will output [1,2]

0
votes

You can read this for better understanding of python arguments passing https://www.python-course.eu/passing_arguments.php

Long story short - you can't override value of argument, you can only create local variable L that points to new list, which will shadow argument L. But on next call of function argument L is still None, unless it will be passed