Code Explanation:
1. Function Definition
def tricky(val, result=[]):
Defines a function tricky with:
val: the value to add to a list.
result=[]: a default argument that is a mutable list.
2. Appending to the List
result += [val]
result += [val] is equivalent to result.extend([val]).
It modifies the list in place, rather than creating a new list.
3. Return Statement
return result
Returns the modified result list.
4. Function Calls & Output
print(tricky(1))
First call: val=1, result=[] (default list used).
result += [1] → result becomes [1].
Returns: [1].
print(tricky(2))
Second call: val=2, result is still the same list used in the first call ([1]).
result += [2] → result becomes [1, 2].
Returns: [1, 2].
print(tricky(3, []))
This time, a new list is passed explicitly as result=[].
result += [3] → becomes [3].
Returns: [3].
print(tricky(4))
Again, uses the original default list, which was mutated to [1, 2].
result += [4] → becomes [1, 2, 4].
Returns: [1, 2, 4].
Final Output
[1] [1, 2] [3] [1, 2, 4]
.png)

0 Comments:
Post a Comment