Python Forum

Full Version: how to add the numbers of a list
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I have a list. Each element is either 1 or 0. I want to add them sequentially.

For example:

I have: attendance = [1, 1, 1, 1]

I declare: cumulativeAttendance = [0] to start with, otherwise I get index errors.

cumulativeAttendance[1] is cumulativeAttendance[0] + attendance[0]
then cumulativeAttendance[1] = cumulativeAttendance[0] + attendance[1]

cumulativeAttendance = [0, 1, 2, 3, 4]

each element of is cumulativeAttendance.append(num2) and num2 is attendance[i] + cumulativeAttendance = [i]

I did this like this, but I think there must be a better way. Why reinvent the wheel?

attnAdded = [0]
    for i in range(0, len(studiAttAll)):
          num1 = studiAttAll[i]
          #print('num1 is ' + str(num1))
          num2 = studiAttAll[i] + attnAdded[i]
          #print('num2 is ' + str(num2))
          attnAdded.append(num2)
    del attnAdded[0]
Is there already a python module to do this? Add the members of a list and write them to a new list such that:
newlist[0] = 0
newlist[1] = newlist[0] + oldlist[1]
newlist[2] = newlist[1] + oldlist[2]
newlist[3] = newlist[2] + oldlist[3]

I have strained my tiny brain this afternoon, any tips greatly appreciated!
def calc_cumulative_attendance(attendance):
    cumulative_attendance = [attendance[0]]

    for item in attendance[1:]:
        cumulative_attendance.append(item + cumulative_attendance[-1])
    
    return cumulative_attendance
    
print(calc_cumulative_attendance([1, 1, 1, 1]))
print(calc_cumulative_attendance([0, 1, 0, 1]))
Output:
[1, 2, 3, 4] [0, 1, 1, 2]
(Apr-07-2019, 11:19 AM)Pedroski55 Wrote: [ -> ]Is there already a python module to do this?

There is built-in module itertools and in there is function accumulate which can be used (in documentation there is also rough code how it is implemented).

>>> from itertools import accumulate
>>> list(accumulate([1, 1, 1, 1]))
[1, 2, 3, 4]
>>> list(accumulate([0, 1, 0, 1]))
[0, 1, 1, 2]