0
I need explanation for this output
def f(a,l=[]): l.append(a) return l print(f(1),f(3)) It prints [1,3] [1,3] But why? l is a local variable , every time when function calls l=[], then output should be [1][3] Explain please
3 Respostas
+ 5
The biggest point here is that f has only 1 default list for parameter l so mutations from one call carry into subsequent calls.
The default value for l isn't a normal local variable. It is more like a global variable that has a local scope. Some languages like c and c++ support static local variables which have a similar effect.
print(f(1),f(3)) breaks down into this sequence:
1. f(1) is called causing default list value for parameter l to become [1].
2. f(3) is called causing default list value for parameter l to become [1, 3].
3. print prints the result from f(1) which is the default list value for parameter l. Since that value is now [1, 3], that gets printed.
4. print prints the result from f(3) which is the default value for parameter l. Since that value is still [1, 3], that gets printed.
You can still get the effect you expected by ensuring l gets assigned a different list.
def f(a,l=[]):
l.append(a)
return l
print(f(1, []),f(3, [])) # [] can be mutated independently from the other [] here.
That outputs: [1] [3]
def f(a, l=None):
if l is None:
l = [] # create new instance of list... don't just reuse the old one.
l.append(a)
return l
print(f(1),f(3))
That outputs: [1] [3]
0
What does the following code output?
x = [[0]*3]*3
x[0][0] = 1
print(x)
0
What does the following code output?
x = [[0]*3]*3
x[0][0] = 1
print(x)