Skip to content
Advertisement

Operand error when using an integer in a list

I’ve been trying to work on this code for hours but keep getting to the same point every time. Basically I’m trying to add up all the values in an array. However, it keeps saying unsupported operand for integer and list. I’m confused why it is saying that because the list consists of integers. This is in python.

hours = [0,0,0,0,0]

i=0 
while i < 5:
    print (days[i])
    hours [i] = int(input('How many hours did you work for the day above? n'))
    i+=1
    print('n')
    
for x in range(len(days)):
    print('n')
    print (days [x])
    print (hours[x])

total = 0
for x in hours:
    total += hours

Above is the fraction of the code that I believe is the problem

    total += hours
TypeError: unsupported operand type(s) for +=: 'int' and 'list'

Above is the error I keep getting

Advertisement

Answer

As @kindall and @Ben Grossmann have correctly pointed out, you’re trying to add a number to a list:

total += hours
  • total is an integer number (total = 0)
  • hours is a list (hours = [0,0,0,0,0])

Change your code to this to make it work:

for x in hours:
    total += x

Side note:

There is an elegant way to get the sum of a list of numbers:

total = sum(hours)

sum() is a built-in function (it comes with Python out-of-the-box). You can read more about it here.

Advertisement