+ 1
Could someone explain the scope of y in following code?
def testFunc(x, y=[]) y.append(x) return y a = testFunc(1) b = testFunc(2) print(b)
5 ответов
+ 8
The scope of y in the given code is the function testFunc.
When the function is defined, the default value for the parameter y is an empty list []. This list is created only once when the function is defined and is stored in memory as part of the function's definition.
Every time the function is called without a value for the parameter y, it will use the same default list object previously created.
In this code, the function testFunc is called twice with different arguments, 1 and 2. When testFunc(1) is called, the value of y is the default list []. The value 1 is appended to this list, and the modified list [1] is returned and assigned to variable a.
When testFunc(2) is called, the value of y is the same list object as before, which now contains [1]. The value 2 is appended to this list, and the modified list [1, 2] is returned and assigned to variable b.
So, the final value of b will be [1, 2]
+ 2
😊 Thank you all
+ 1
It is only available in the function and cannot be referred to outside the function
0
y is a list. Is the argument of the function. (Was that what you were asking?)
0
I mean after running code it outputs [1, 2], as I know all variables inside a function are local, but it looks y is a global variable