Anyone explain this please......
def f(i,list1=[]):
list1.append(i)
return list1
f(1)
f(2)
print(f(3))
Output: [1,2,3].
I cannot understand this, because everytime my list1 is initialized as a empty list.
Can anyone explain this??
Method #1 : Using * operator We can employ * operator to multiply the occurrence of the particular value and hence can be used to perform this task of adding value multiple times in just a single line and makes it readable.
append() adds a list inside of a list. Lists are objects, and when you use . append() to add another list into a list, the new items will be added as a single object (item).
Append in Python is essential to add a single item at the end of a list, array, deque, or other collection types and data structures on the go.
You should not include the list creation in the argument declaration.
This is because the line that says def f(i, list1=[]):
actually creates a new list when it gets to the []
. This happens when the function is created.
Each time the function runs, it is re-using that same list object.
Think of it in terms of how the program runs, line by line. In effect the def
line ends up looking like this when it runs:
def f(i, list1=<a-new-list-that-I-just-created>):
And each time the function is called, the list1 default value is not a new list, but the list that was created when the function was defined.
I believe this is what you want, if you want to avoid this, is:
def f(i, list1=None):
if not list1:
list1=[]
list1.append(i)
return list1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With