+ 1
Python, Why?
Why is not the output : [[1,1,1,1], [1,1,1,2],...., [2, 2, 2, 1], [2, 2, 2, 2]] , what's happen?! https://code.sololearn.com/cZdM9X1R6ZYD/?ref=app
2 Réponses
+ 1
The answer is simple
a = [1]
b = a
a.append(2)
Now b == [1, 2]
Because we said that b=a
The same thing is happening when passing the argument l recursively and appending it to list, every time you update l, every l in list gets "updated"
0
because you are using mutable type 'list' as default arguments..
"When Python executes a “def” statement, it takes some ready-made pieces (including the compiled code for the function body and the current namespace), and creates a new function object. When it does this, it also evaluates the default values."
source :- https://web.archive.org/web/20200221224620/http://effbot.org/zone/default-values.htm
---------------------------------------------------
SOLUTION :
use mutable types as default argument like this -->
def func( lst=None ):
if lst is None :
lst=[]
#your code goes here
https://code.sololearn.com/cCDNe6i5vNFh/?ref=app