0

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 Answers 2

1

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]

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for catching that typo @MikeScotty.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.