Code Explanation:
1. Function Definition: append_and_return
def append_and_return(val, data=[]):
Defines a function that takes:
val: a value to append.
data: a list (optional), defaulting to [].
Important: The default value [] is mutable and is created only once at function definition time — not each time the function is called.
2. Appending to the List
data.append(val)
return data
The function appends val to the data list.
Then it returns the modified data list.
3. First Call: x = append_and_return(1)
x = append_and_return(1)
Since data is not passed, the default list ([]) is used.
1 is appended to it → data becomes [1].
So, x = [1].
4. Second Call: y = append_and_return(2)
y = append_and_return(2)
Again, no list is passed, so the same default list is reused.
2 is appended → data becomes [1, 2].
So, y = [1, 2].
This is the key issue: the default [] persists across calls unless explicitly overridden.
5. Third Call: z = append_and_return(3, [])
z = append_and_return(3, [])
Here, a new empty list [] is explicitly passed.
3 is appended → list becomes [3].
So, z = [3].
6. Final Output
print(x, y, z)
x and y share the same list: [1, 2]
z is a new independent list: [3]
Output
[1, 2] [1, 2] [3]
Download Book - 500 Days Python Coding Challenges with Explanation


0 Comments:
Post a Comment