Kaleembukhari
Kaleembukhari

Reputation: 5

'int' object not iterable error: Python

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))

Upvotes: 0

Views: 203

Answers (1)

Sreeram TP
Sreeram TP

Reputation: 11907

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.!!

Upvotes: 1

Related Questions