Respected members, why does my Python function remember the old list?
Respected members,
I am a mathematics teacher learning Python so that I can teach my Class 9 students properly. I wrote a small function to collect marks, and something very strange is happening. Kindly see:
def add_mark(mark, marks=[]):
marks.append(mark)
return marks
print(add_mark(45)) # [45]
print(add_mark(78)) # [45, 78] I expected [78]
print(add_mark(62)) # [45, 78, 62]
Each time I call the function without the second argument, I expected a fresh empty list. But it keeps the old values. My students noticed it before I did, which was a little embarrassing for the teacher.
Is this a bug in Python? We are using Python 3.12 on the school lab computers. Kindly also guide me how to explain it to fourteen year old children, because "it is like that only" will not satisfy them.
Thanking you,
Lakshmi
Accepted answer
Get the best of #read-the-docs weekly
One email each Monday with the most useful posts. No spam; unsubscribe in one click.
Comments
Sign in to join the conversation.
Sign in to commentAccepted answer