Can anyone explain this really basic Python code for me?

I recently went for an interview for a Python developer position. One of the questions was the following code. I just had to write a conclusion.

def extendList(val,list=[]): list.append(val) return list list1 = extendList(10) list2 = extendList(123,[]) list3 = extendList('a') print "list1 = %s " %list1 print "list2 = %s " %list2 print "list2 = %s " %list3 

Conclusion:

 list1 = [10, 'a'] list2 = [123] list2 = [10, 'a'] 

I am trying to understand why the first list list1 has the value 'a' .

EDIT

I checked all the links and found out that this is python "gotcha" for beginners, but I want to thank the answers, I can not choose both, so I go with the first one.

+5
source share
2 answers

list1 has 'a' because the list created with extendlist('a') is added to the same list as extendList(10)

This is, without a doubt, the result of detail in how Python deals with default arguments and the state model. You can even claim that this is a mistake because it violates the closure property (if it is assumed that the Python methods are closures).

For example, equivalent code in Ruby:

 def extendList(val, list=[]) list << val return list end 

returns

 extendList(10) # => [10] extendList(123, []) # => [123] extendList('a') # => ['a'] 

This is in Ruby, because Ruby methods are closures, i.e. Each method call carries a local environment around it.

+1
source

Actually, it’s not so simple, it’s a little python eyedropper: Mutable Default Parameter

Compare with printing after each function call:

 >>> def extendList(val,list=[]): ... list.append(val) ... return list ... >>> list1 = extendList(10) >>> print "list1 = %s " %list1 list1 = [10] >>> list2 = extendList(123,[]) >>> print "list2 = %s " %list2 list2 = [123] >>> list3 = extendList('a') >>> print "list2 = %s " %list3 list2 = [10, 'a'] 

also:

 >>> list1 is list2 False >>> list1 is list3 True 
+1
source

Source: https://habr.com/ru/post/1211962/


All Articles