Nouvelle formation ! Tous les codeurs devraient apprendre l'IA générative !
Essayez une leçon gratuite0
def extend(num, list=[]): list.append(num) return list x=extend(1) y=extend(2) print (x,y)
How output is [1,2][1,2]
5 Réponses
+ 5
I slightly remember someone asked a similar question but I can't find it. Probably it wasn't properly tagged that search engine doesn't see it.
In short, the same `list` was returned by extend(), that's why both <x> and <y> has similar content. You can verify that by checking their object ID
print( id( x ), id( y ) )
Note: Please avoid using built-in class and/or function name for naming variables or function parameters. You might accidentally override the said class/function definition, and end up not able to utilize the original class/function for their original purpose.
// avoid use of `list` as parameter name and return value
def extend( num, lst = [] ):
# code
return lst
You might also reconsider `extend` as function name because `list` class also has `extend` method which is used to add contents of another iterable object as new items for current `list` object.
+ 5
Somvir Dhaka ,
> first of all, do not use python reserved names like *list*, better use *lst*.
> a function in python will be compiled to a *function object* before its first use. the default parameter lst=[] will be initialized only when the first call is executed. all following calls in a running program do *NOT* re-initialize the mentioned parameter.
When the function is used multiple times (multiple calls of the function by the program), the function *is still the same object*. the default parameter is part of the function (header), it will keep all members that have been appended to it during a running program.
> to make it more clear i have inserted an additional print statement:
def extend(num, lst=[]):
lst.append(num)
return lst
x=extend(1)
print(x) # <<< inserted this line output is [1]
y=extend(2)
print (x,y)
How output is
[1]
[1,2][1,2]
+ 3
Because the function adds new values to the same list:
list.append(num)
def extend(num, list=[]):
list.append(num)
return list
x=extend(1)
print(x)
y=extend(2)
x.append(3)
print(x==y, y)
The names are different, and the data storage address is the same.
0
Thanks
0
Is this case is same in recursive function call