Æther
Æther

Reputation: 35

Adding using a for loop in python

I'm try to add some numbers to 36 in sequence. For example I have 36, then my list of number such as 10, 20, and 30. I want my program to add 36 to ten, take the sum of that, add it to 20, and so on. I'm probably making myself look like an idiot here, but I'm really trying to learn.

Here is one I tried:

x = [11, 152, 620, 805, 687, 1208, 866, 748, 421, 434, 67, 56, 120, 466, 143, 1085, 401]         
b = sum(36, x)
print b

or

x = [11, 152, 620, 805, 687, 1208, 866, 748, 421, 434, 67, 56, 120, 466, 143, 1085, 401]       
y = 0
for int in x:
    print y + x

Upvotes: 1

Views: 38

Answers (2)

Ray Toal
Ray Toal

Reputation: 88488

Maybe it is not well known that sum takes a second parameter that defaults to zero, but your question is simply asking for this to be called out!

Try

sum(x, 36)

It actually works.

>>> sum([1,2,3], 36)
42
>>> sum([], 36)
36

See the docs.

It looks like when you tried sum(36, x) that you just had the parameters reversed. It is okay to say:

sum(x, start=36)

That does exactly what you want; it starts with 36 then accumulates all the values in x.

And it does it without a for loop, which is actually nice.

Upvotes: 2

chepner
chepner

Reputation: 532538

Short and sweet:

b = 36 + sum(x)

Upvotes: 1

Related Questions