Need an explanation about the output | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Need an explanation about the output

Why is the answer [0,1]? What is the output of this code def f(x, a = []): for i in range (x): a.append (i * i) print (a) f(2)

22nd Jan 2020, 1:14 PM
Shamil Erkenov
Shamil Erkenov - avatar
7 Answers
+ 2
2 is passed as argument to the function f a = [] is an empty array In the loop i takes values 0 and 1 0*0=0 is added to the array 1*1=1 is added to the array The array is printed [0,1]
22nd Jan 2020, 1:21 PM
Mihai Apostol
Mihai Apostol - avatar
+ 3
Ok,you function print an array that we each time add to its end the multiplication of numbers betwen 0 and 1 bythemselves. The first iteration i=0 so i*i=0*0=0 so we add 0 to our array a[] . The second iteration : i=1 and 1*1=1 we add 1 to the end of the array a so a becomes a=[0,1] Remark that we dont arrive to 2 because Range(2) stops at 1
22nd Jan 2020, 1:21 PM
mohamed Issati
mohamed  Issati - avatar
+ 2
Thank you guys ♥️
22nd Jan 2020, 1:24 PM
Shamil Erkenov
Shamil Erkenov - avatar
+ 2
Oh, sorry I got that
22nd Jan 2020, 1:33 PM
Shamil Erkenov
Shamil Erkenov - avatar
+ 1
One more question isn't append about adding to the list, why in this case it goes after a.
22nd Jan 2020, 1:26 PM
Shamil Erkenov
Shamil Erkenov - avatar
0
You're welcome.
22nd Jan 2020, 1:25 PM
Mihai Apostol
Mihai Apostol - avatar
0
Not sure what are you asking. a = [] is empty a = [0] after we add/append 0 to list a = [0, 1] after we add/append 1 to the list
22nd Jan 2020, 1:30 PM
Mihai Apostol
Mihai Apostol - avatar