The intended objective of function foo
is to add the number provided as argument to the list and, in case it is 0, reset the list. First I wrote this program:
def foo(n, bar = []):
if n == 0:
bar = []
print("list empty")
else:
bar.append(n)
for y in bar:
print(y, end=', ')
print()
foo(5)
foo(3)
foo(0)
foo(6)
output:
5,
5, 3,
list empty
5, 3, 6,
but it looks like bar = []
is ignored. Then I changed bar = []
with bar.clear()
and it works as I thought:
def foo(n, bar = []):
if n == 0:
bar.clear()
print("list empty")
else:
bar.append(n)
for y in bar:
print(y, end=', ')
print()
foo(5)
foo(3)
foo(0)
foo(6)
output:
5,
5, 3,
list empty
6,
I haven't understood why bar.clear()
works differntly from bar = []
since clear()
should
Remove all elements from the set.
so the same thing bar = []
does.
Edit: I don't think my question is a duplicate of “Least Astonishment” and the Mutable Default Argument, I'm aware that
The default value is evaluated only once.
(from the official tutorial) but what I am asking is, why bar = []
doesn't edit (in this case clear) the list, while append and clear does?