voltron
voltron

Reputation: 23

How can I add elements to a list using a for loop?

I'm using open(filename) to open a file that contains the numbers 73, 85, 66, 0, and 99.

I'm adding each number to a list named values. Now I want to get the mean of all of the numbers. I'm trying to sum the values using a variable named sum and then print the sum.

values = []
for i in values:
    sum = sum + i
print sum:

This code is giving me the following error: TypeError: unsupported operand type(s) for +: 'builtin_function_or_method' and 'int'

Upvotes: 0

Views: 61

Answers (2)

PM 2Ring
PM 2Ring

Reputation: 55469

You're using sum as a variable name, which you haven't initialised. But sum is the name of a built-in function, so you shouldn't use it as a variable name because it can lead to problems like this. :) Your code is telling Python to add the integers in values to a function, so it complains. But this works:

values = [1, 2, 3, 4]

total = 0
for i in values:
    total = total + i
print total

output

10

FWIW, the above code would work if we used sum instead of total to store the current accumulated sum because it gets initialised before the start of the loop. But that's not a good idea, since it means you can't access the proper sum() function if you need it later. Also, it's a bit confusing to people reading your code.


Or you could just use the sum() function, since it's designed to add together the contents of an iterable:

print sum(values)

output

10

Upvotes: 2

Pikamander2
Pikamander2

Reputation: 8299

When you're calling sum = sum + i, you haven't given sum a value yet. You can't add 1 to an undefined variable.

Declare sum = 0 before your code block and it should fix the problem.

Also, there shouldn't be a colon after your print statement. Was that a typo, or is that actually in your code?

Upvotes: 0

Related Questions