1

I want to be able to add values to a list. For example, I have these two list:

alist = [1,3,5,7,9]
blist = [0]

I want to insert a value to blist that is the value of alist with all values prior to it within alist. For example, blist would be the following:

blist = [0,1,4,9,25] 

Since 1 is the first value in alist it stays the same, then I do 1+3 =4, 1+3+5 =9, etc. However, I'm very confused about how I need to go about implementing this. I have the following piece of code:

list1 = [1,2,3,4,5]
list2 = [0]
x = 0

while x < len(list1):
    blist.append(alist[0])

This would append the first value at position 0 to list2 and would make list2 = [0,1]. However, I don't understand how to go about in order to add the values the way I need to.

4
  • I edited your blist = [o] to blist = [0] because I was pretty sure you didn't mean blist = ['o']. FYI blist = [o] is a NameError Commented Apr 8, 2019 at 22:26
  • if you're not married to doing this is pure python, I'd take a look at numpy.cumsum Commented Apr 8, 2019 at 22:26
  • Are you missing a 16 in the desired result? Commented Apr 8, 2019 at 22:28
  • @cosmic: Your edit deleted all of the actual question from your question. Don't do that. Commented Apr 9, 2019 at 0:17

3 Answers 3

8

itertools has a nice accumulate function that does this (and more):

from itertools import accumulate
alist = [1,3,5,7,9]
blist = [0] + list(accumulate(alist))
# blist is now [0, 1, 4, 9, 16, 25]
Sign up to request clarification or add additional context in comments.

1 Comment

Minor note: In modern (3.5+) Python, you could build blist in one step without temporary lists involved with just blist = [0, *accumulate(alist)].
3

This can be done with a list comprehension

blist = [sum(alist[:i]) for i in range(len(alist) + 1)]

gives

[0, 1, 4, 9, 16, 25]

Comments

2

Just for sake of completion ill add a numpy answer

import numpy as np
alist = [1,3,5,7,9]
blist = [0]
blist = blist + list(np.cumsum(alist))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.