If I set an empty list as the default parameter of a function I get a difference in behavior when I add elemets with the append method or when I use the "+" operator. Could someone explain why this happens?
WITH APPEND
def append_to(n, my_list = []):
for i in range(n):
my_list.append(str(i))
return my_list
a = append_to(5)
print(a)
b = append_to(10)
print(b)
OUT:
['0', '1', '2', '3', '4']
['0', '1', '2', '3', '4', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
WITH "+"
def append_to(n, my_list = []):
for i in range(n):
my_list = my_list + [str(i)]
return my_list
a = append_to(5)
print(a)
b = append_to(10)
print(b)
OUT:
['0', '1', '2', '3', '4']
['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']