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

25th Apr 2023, 7:49 PM
Amin Takhsideh
Amin Takhsideh - avatar
5 Respuestas
+ 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]
25th Apr 2023, 8:45 PM
Anonymous
Anonymous - avatar
+ 2
😊 Thank you all
25th Apr 2023, 9:00 PM
Amin Takhsideh
Amin Takhsideh - avatar
+ 1
It is only available in the function and cannot be referred to outside the function
25th Apr 2023, 8:35 PM
Anonymous
Anonymous - avatar
0
y is a list. Is the argument of the function. (Was that what you were asking?)
25th Apr 2023, 8:27 PM
Ugulberto Sánchez
Ugulberto Sánchez - avatar
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
25th Apr 2023, 8:37 PM
Amin Takhsideh
Amin Takhsideh - avatar