Key Concepts:
🔹 lst=[] is a mutable default argument.
-
In Python, default argument values are evaluated only once when the function is defined, not each time it’s called.
-
That means the same list (lst) is reused across multiple calls unless a new one is explicitly provided.
Step-by-Step Execution:
First Call:
-
val = 1
-
No list is passed, so lst defaults to []
1 is appended to the list → list becomes [1]
-
It returns [1]
Second Call:
-
val = 2
-
Still using the same list as before ([1])
2 is appended → list becomes [1, 2]
-
It returns [1, 2]
✅ Output:
How to Avoid This Pitfall:
To make sure a new list is used for each call, use None as the default and create the list inside the function:
Now each call will work with a fresh list.


0 Comments:
Post a Comment