What is this? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 4

What is this?

Can anyone solve it. Why 1st code show [2][2] as output. Why 2nd code show output 12. What is main difference. https://code.sololearn.com/cii43HyTVUaV/?ref=app https://code.sololearn.com/c5b0sDSedUWQ/?ref=app

22nd Feb 2019, 5:08 PM
Maninder $ingh
Maninder $ingh - avatar
3 Answers
+ 6
Python creates keyword parameters when you define a function not when you call it. https://docs.python-guide.org/writing/gotchas/
23rd Feb 2019, 11:48 AM
Mert Yazıcı
Mert Yazıcı - avatar
+ 4
I'm not an expert. I guess the main thing is next. The both scripts declare list a=[] and this list is the same for any call of function. First script: - twice we increase the first value of this list - function return the same list (c=b=a[]) Then we display the same list with one item with value=2. ([2]) Second script do the same thing but return value of first item. At first time it 1, at second time it is 2
22nd Feb 2019, 6:12 PM
Earl_Grey
Earl_Grey - avatar
0
def foo(a = [0]): a[0] += 1 return a b = foo() + [] print (id(b)) c = foo() print(f'{b}{c}') print(id(b),id(c)) # now output is [2][2] ? Try line 5 with and wo []
23rd Feb 2019, 10:34 AM
tamaslud
tamaslud - avatar