Code Explanation
Step 1: Function Definition
def append_item(item, container=[]):
container.append(item)
return container
A function append_item is defined with two parameters:
item: the value to add.
container: defaults to [] (an empty list).
Important: In Python, default argument values are evaluated once at function definition time, not every time the function is called.
That means the same list ([]) is reused across calls if no new list is passed.
Step 2: First Call
print(append_item(1), ...)
append_item(1) is called.
Since no container argument is provided, Python uses the default list (currently []).
Inside the function:
container.append(1) → list becomes [1].
return container → returns [1].
So, the first value printed is [1].
Step 3: Second Call
print(..., append_item(2))
append_item(2) is called.
Again, no container is passed, so Python uses the same list that was used before ([1]).
Inside the function:
container.append(2) → list becomes [1, 2].
return container → returns [1, 2].
So, the second value printed is [1, 2].
Step 4: Final Output
print(append_item(1), append_item(2))
First call returned [1].
Second call returned [1, 2].
Final Output:
[1] [1, 2]
Download Book - 500 Days Python Coding Challenges with Explanation
.png)

0 Comments:
Post a Comment