Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Explanation for a code needed : Appending the values to list in python [duplicate]

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??

like image 272
Israel Avatar asked Nov 17 '17 05:11

Israel


People also ask

How do you add duplicates to a list in Python?

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.

How do you append a list to a list in Python?

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).

Why append is used in Python?

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.


1 Answers

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
like image 177
JGC Avatar answered Nov 15 '22 00:11

JGC