say you have a list, b, you don't know how many items are in there, but how could you add up all the items? for example, if your list is [2,4,5,8,10] is it possible to find the sum of all the numbers? so it will give you 29?

i've been thinking, is there a way to find out the amount of items in a list you have? then i can just do:

b = [1,2,5,8,300,2568.......]
k = 0
m = how many items
while k <=m:
    for n in range (m+1):
        k = k + b[n]
print (k)

i understand neither of those commands are very common, however at this point either would really help me out...

Recommended Answers

All 3 Replies

len(b)

Will give you the length of b.

s = 0
for i, value in enumerate(b):
    s += value

That will give you the sum of all elements in b.

You could also do it like this:

s = 0
for i in range(len(b)):
    s += b[i]

Or:

sum(b)

;)

In your example, why do you have the while loop?

Also, don't add 1 to the length of b in your call to range.

Get rid of the while loop, fix your call to range and set m equal to len(b) and you have the equivalent of my second example.

thanks a lot, nah i don't even need the while loop with something as simple as sum(b) ... but the idea i was trying to use was similar to your second example...

i've been wondering what len means, i've seen it in a couple syntax messages...

you're right that range(m+1)should be just range(m), i forgot that the first number in list b is be b[0], not b[1],...of course now i'll just use sum(b) .

thanks! :)

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.