Step-by-Step Explanation:
-
Initialize a list:
-
A list backpack is created with one item: [0].
-
-
Call the function:
-
The list backpack is passed to the function add_item.
-
Inside the function, the parameter bag refers to the same list object as backpack.
-
-
Inside the function:
-
This modifies the original list in place.
+= on a list performs in-place addition, equivalent to bag.extend([1]).
-
So bag (and therefore backpack) becomes [0, 1].
-
-
Print the list:
-
The backpack list has been changed, so it prints:
-
✅ Output:
Key Concept:
-
Mutable objects like lists can be modified inside functions.
-
Using += on a list modifies the original list in-place.


0 Comments:
Post a Comment