24
loading...
This website collects cookies to deliver better user experience
def foo(a = []):
a.append(5)
return a
5
to it...>>> foo([1,2,3,4])
[1,2,3,4,5]
>>> foo([1,2,3,4,5,6])
[1,2,3,4,5,6,5]
>>> foo()
[5]
>>> foo()
[5,5]
>>> foo()
[5,5,5]
5
in it a single element list which would look like [5]
..?list
or a mutable datatype i.e. it can be modified and that's what is happening here.a = []
def foo():
a.append(5)
return
>>> foo()
[5]
>>> foo()
[5,5]
>>> foo()
[5,5,5]
>>> def eggs():
print('eggs() executed')
return []
>>> def foo(a = eggs()): # as soon as you hit enter after the definition it outputs 'eggs() executed'
a.append(5)
return a
eggs() executed
>>> def eggs():
print('eggs() executed')
return () # this time we use a tuple instead as these are immutable
>>> def foo(a = eggs()): # as soon as you hit enter after the definition it outputs 'eggs() executed'
a += (5,)
return a
eggs() executed
>>> foo()
(5,)
>>> foo()
(5,)