+ 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
3 Antworten
+ 6
Python creates keyword parameters when you define a function not when you call it.
https://docs.python-guide.org/writing/gotchas/
+ 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
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 []