0

I am new to python, and I am trying to run the code given below. But it keeps throwing an error:

int object not iterable.

I want to calculate the sum of sqaures in an array. Here is the code. The variable product is already defined, so that is not the worrisome part.

def sumofsquares(x1):
    result=[]
    for i in range (len(x1)):
        result.append(sum((x1)[i]**2))
    return result

print (sumofsquares(product))
1
  • 1
    1. Please fix the indentation. 2. What is product? Commented Nov 16, 2017 at 7:28

1 Answer 1

1

Assuming product is a list containing the numbers you want to find the sum of sqaures, you can iterate through the list and calculate squares of each number and add it to a list called result. At last you can return the sum of that list.

In codes you can do like this..

def sumofsquares(x1):
    result = [] # list to store squares of each number

    for i in range(len(x1)): # iterating through the list
        result.append(x1[i] ** 2) # squaring each number and appending to the list

    return (sum(result)) # returning the sum of the list

product = [1, 2, 3] # declaring the array to find sum of sqaure
print (sumofsquares(product)) # calling the function and displaying the return value

# Output
14

Hope this helps.!!

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks alot. It worked perfectly fine. Also, can you please explain the logic behind the given error? So that I can understand it better.
Happy to hear it helped. Accept and upvote the answer if it did.
Also, you were doing result.append(sum((x1)[i]**2)) which will also give you an error. Because the list item must be acessed like listname[index]. Also, the sum function must be applied to a list or more than 1 number.
Let me know if you have further queries about the error.!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.