0

I have a list name:

my_list = [1,2,3,4,5,6]

I want to output to look like this, 1, 3(1+2),6(1+2+3), 10(1+2+3+4), ... how can I do this in python? Thank for reply in advance

jamylak
  • 128,818
  • 30
  • 231
  • 230
user1407199
  • 163
  • 1
  • 1
  • 9

3 Answers3

2

In Python 3.2+ it's as simple as this:

>>> from itertools import accumulate
>>> nums = [1,2,3,4,5,6]
>>> list(accumulate(nums))
[1, 3, 6, 10, 15, 21]

Documentation

jamylak
  • 128,818
  • 30
  • 231
  • 230
2
total = 0
for i, element in enumerate(my_list):
    total += element
    print "%d (%s)" % (total, '+'.join(my_list[:i+1])
John Szakmeister
  • 44,691
  • 9
  • 89
  • 79
1

Try this one-liner:

b = [sum(a[:i+1]) for i, x in enumerate(a)]

This is not super-efficient (and that's an understatement), because you are summing again and again the entire elements...

for a more efficient solution you can do something like this:

result = []

for i, current in enumerate(a):
    if result:
        last = result[i - 1]
    else:
        last = 0
    result.append(last + current)

print(result)
>> [1, 3, 6, 10, 15, 21]
zenpoy
  • 19,490
  • 9
  • 60
  • 87