简体   繁体   中英

How can i sum every number in list with each other in python?

So, i have a list of numbers:

list = [4,5,65,94,3]

This loop sums the first number in list with every number in list:

for i in list:
    sum = i + list[0]

How can i move to the next item in list so that my loop would sum every number in that list with each other?

So, there's two misconceptions here.

First, that loop isn't doing what you describe. Provided that sum is defined outside of it, the only values you are adding that will stick after the loop is the last element in the list and whatever is in the first position of the list. For your current list, the sum would be 7.

Second, there's a handy function to do this already - sum - which would make short work of your task.

sum([4,5,65,94,3])

But if you insist on doing this yourself, you have to set up a few things:

  • Ensure the variable you're accumulating to is a sentinel value for your math operation. For addition, it has to start at 0. For multiplication, it starts at 1.
  • Add to your original value; don't overwrite its value. This would mean either total = total + i or total += i .
  • Remember that Python's for loop is actually a for-each loop. i will advance through your list and be bound to each value in turn.

To fix the code, you'd want to do this:

total = 0
li = [4,5,65,94,3]
for i in li:
    total += i

As a final note, avoid shadowing function names. list and sum are already defined as functions, and you really don't want to go shadowing them.

Not exactly sure what you are trying. To find the sum of a list in python, you just need to do this:

for i in li:
    total += i

What you are currently doing is changing the value of sum each iteration to equal the i plus the first element of your list. This will make your sum equal to 7 at the end of the loop because it sums the final element (3) with the first element (4).

Alternatively, python has a built in function to sum the numbers in a list so your code can be simplified to this:

li = [4,5,65,94,3]
total = sum(li)

Edit: As others have pointed out, avoid naming your variables the same as functions.

Or if you do want to iterate using indexes, you can do that using the range function like this

for i in range(len(list)):

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM