Code Explanation:
Function definition (evaluated once)
def tricky(val, lst=[]): defines a function with a default list.
That default list is created once at definition time and reused on later calls if you don’t pass lst.
Function body (what each call does)
lst.append(val): mutates the list in-place by adding val.
return sum(lst): returns the sum of all numbers currently in lst.
First call: tricky(10)
No lst passed → uses the shared default list (currently []).
After append: lst becomes [10].
sum([10]) → 10.
Result: 10 (and the shared default list now holds [10]).
Second call: tricky(20)
Still no lst passed → uses the same shared list (now [10]).
After append: lst becomes [10, 20].
sum([10, 20]) → 30.
Result: 30 (shared list is now [10, 20]).
Third call: tricky(30, [1])
An explicit list [1] is provided → not the shared default.
After append: list becomes [1, 30].
sum([1, 30]) → 31.
Result: 31 (this separate list is discarded after the call unless stored elsewhere).
Final print
Prints the three return values separated by spaces.
Output:
10 30 31
Download Book - 500 Days Python Coding Challenges with Explanation
.png)

0 Comments:
Post a Comment