-1

logic: read list using for loop and add all its elements together and, In end print all the iteration value together in the list

input

lis=[1,1,1,1,1]
ore=[]
for t in lis:
    ore.append(sum(lis[0:lis.index(t)+1]))
    

print(ore)

output

[1, 1, 1, 1, 1]

expected

[1,2,3,4,5]

I have no idea why I am getting output like this one, also want to know about the mechanism of this kind of output. Any possible help is appreciated.

ooo
  • 512
  • 1
  • 7
  • 27

3 Answers3

1
  1. The correct way to iterate over both indexes an items with a list is to use enumerate, not to try to find the index after the fact; that’s slow, and fails when the list has duplicate elements (like you found out).

    for i, t in enumerate(lis):
        ore.append(sum(lis[0:i+1]))
    
  2. Using sum on a slice that grows by one element each time is also inefficient. You know the sum is only changing by the current value in each iteration, so:

    s = 0
    
    for t in lis:
        s += t
        ore.append(s)
    
Ry-
  • 218,210
  • 55
  • 464
  • 476
0

Your output is wrong because t represents an item in the lis, not the current index.

Here's the fixed code

lis=[1,1,1,1,1]
ore=[]
for i, t in enumerate(lis):
    ore.append(sum(lis[0:i+1]))

print(ore)

Output:

[1, 2, 3, 4, 5]
WyattBlue
  • 591
  • 1
  • 5
  • 21
0

you can use np.cumsum() from the numpy library:

import numpy as np
np.cumsum(lis)

returns: a numpy array: [1, 2, 3, 4, 5]

vsminkov
  • 10,912
  • 2
  • 38
  • 50
KKay24
  • 1