I have 2 lists:
a=[0,1,5,7]
b=[2,10,6,3]

I need to get this list :

c=[(b[0]+a[0]),(b[0]+b[1]),(b[0]+b[1]+b[2]),(b[0]+b[1]+b[2]+b[3])]

I tried doing this using a for loop:

c=[(b[0]+a[0])]
for i in range(0,(len(b)-1)):
    for p in range(i+1,len(b)):
        if i==0:
            c.append((b[i]+b[p]))
            
        else:
            c.append((c[i]+b[p]))

I am supposed to get [2,12,18,21] but I am getting [2, 12, 12, 12, 18, 15, 15]

Where am I going wrong in the for loops?

Thank you :)

Recommended Answers

All 2 Replies

I would do it like this with list comprehension

Little funny sequence as it includes only one element from a in formula.

>>> b[:2]
[2, 10]
>>> c=[a[0]+b[0]]
>>> c.extend([sum(b[:x]) for x in range(2,len(b)+1)])
>>> c
[2, 12, 18, 21]
>>>

Thank you tonyjv!!
It worked perfectly.
I guess I should maximize using Python idioms where ever possible...makes it simpler.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.