Could you please explain me? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

Could you please explain me?

Why is the output [1,0,0,0]6 What is the output of this code? A=[1,2,3,4] pos, sum=0,0 for val in A[:Len(A)-1]: A[pos+1]=0 sum=sum+val pos=pos+1 print(A,sum)

26th Jan 2020, 11:39 AM
Shamil Erkenov
Shamil Erkenov - avatar
4 Answers
+ 1
1. ok I understood how we got "3" but what is 0 about? Arrays (or lists) start counting from index 0. It can be omitted when slicing a list. I just mentioned it to get a full picture. 2. how do you know that it relates to EVERY element beyond 0, why not only to "[1]" cz "+1" It is inside a for loop. You access each element by its index of A[pos+1]. So you work with A[1], A[2] and A[3] that correspond to [2, 3, 4]. For every element in this range you assign element's value to 0, thus making a list [0, 0, 0]. When you print the list, you concatate the unchanged value of [1], to the 'new' list [0, 0, 0], getting [1, 0, 0, 0]. 3. I didn't get it at all, are these indexes of the list? And how do you know then that it's about indexes and not about the [1,2,3,4] itself? When you want to access an index of a list, you use the syntax element[index]. That's why you access elements by index in a previous step, with A[pos]. When you initiate a for loop, you name elements as val. Values or vals in list correspond to 1, 2, 3, 4 respectively. You declare a variable sum with value of 0 first. First iteration: 0 = 0 + 1 (element with index A[0] has a value of 1) Second iteration: 1 = 1 + 2 (element with index A[1] has a value of 2, which add to a sum that we got from before) Third iteration: 3 = 3 + 3 There should've been a fourth iteration but we limit our range to range(len(A) - 1). Thus limiting the number of iterations to - 1, in our case 3. That's how you get the sum of 6.
26th Jan 2020, 12:46 PM
Khatakh
Khatakh - avatar
+ 2
1) For val in A[0:3] # ok I understood how we got "3" but what is 0 about? 2) A[pos+1] # how do you know that it relates to EVERY element beyond 0, why not only to "[1]" cz "+1" 3) sum=sum+val is the same as sum=0+1+2+3=>6 # I didn't get it at all, are these indexes of the list? And how do you know then that it's about indexes and not about the [1,2,3,4] itself? Sorry for bothering and thank you for your help
26th Jan 2020, 12:34 PM
Shamil Erkenov
Shamil Erkenov - avatar
+ 2
Oh, man, thank you very much!!!
26th Jan 2020, 1:08 PM
Shamil Erkenov
Shamil Erkenov - avatar
0
len(A) = 4 # 4 elements in a list. This way it can be presented as: for val in A[0:3] sum = sum+val is the same as sum = 0 + 1 + 2 + 3 => 6 A[pos+1] = 0 # You assign the value of 0 to every element with index beyond 0 A[0] = 1, A[1] = 0, A[2] = 0, A[3] = 0 Combine that and we get: [1, 0, 0, 0] and a sum, which is 6.
26th Jan 2020, 12:17 PM
Khatakh
Khatakh - avatar