When you define a function in Python with an array parameter, what is the scope of that parameter?
This example is taken from the Python tutorial:
def f(a, L=[]): L.append(a) return L print f(1) print f(2) print f(3)
Prints:
[1] [1, 2] [1, 2, 3]
I'm not quite sure if I understand what's happening here. Does this mean that the scope of the array is outside of the function? Why does the array remember its values from call to call? Coming from other languages, I would expect this behavior only if the variable was static. Otherwise it seems it should be reset each time. And actually, when I tried the following:
def f(a): L = [] L.append(a) return L
I got the behavior I expected (the array was reset on each call).
So it seems to me that I just need the line def f(a, L=[]):
explained - what is the scope of the L
variable?
A variable created in the main body of the Python code is a global variable and belongs to the global scope. Global variables are available from within any scope, global and local.
Default arguments in Python functions are those arguments that take default values if no explicit values are passed to these arguments from the function call. Let's define a function with one default argument. def find_square(integer1=2): result = integer1 * integer1 return result.
The scope of a variable refers to the context in which that variable is visible/accessible to the Python interpreter.
Introduction to Python default parameters When you define a function, you can specify a default value for each parameter. In this syntax, you specify default values ( value2 , value3 , …) for each parameter using the assignment operator ( =) .
The scope is as you would expect.
The perhaps surprising thing is that the default value is only calculated once and reused, so each time you call the function you get the same list, not a new list initialized to [].
The list is stored in f.__defaults__
(or f.func_defaults
in Python 2.)
def f(a, L=[]): L.append(a) return L print f(1) print f(2) print f(3) print f.__defaults__ f.__defaults__ = (['foo'],) # Don't do this! print f(4)
Result:
[1] [1, 2] [1, 2, 3] ([1, 2, 3],) ['foo', 4]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With