Python Basics IteratingLists

Hii @All,

Can someone please help in understanding below given logic assigned to the variable “b”

a=[3,1,4,2]
b=[sum(a[0:x+2]) for x in range(0,len(a))]
print(b)

Thank you!

Hello @Jethan

Check the explanation below:

len(a) = 4 → in range(4) there is 0, 1, 2, 3.
step 1
b = [sum(a[0:0+1]) = 1, because x = 0 in range
step 2
b = [sum(a[0:1+1]) = 1+2 = 3, because we take numbers from 0 to 2 index
then we do same and we have:
b = [1, 3, 6, 10]
You can run it yourself, you will understand it)

Thanks,
KodeKloud Support