Reputation: 3
I am trying to add all the elements in a list but it keeps popping up with unsupported operand for int and string any idea?
total_years = 0
for i in range(len(str(years_list))):
total_years += str(years_list[i])
print(years_total)
if I use int it comes up with IndexError: list index out of range
Upvotes: 0
Views: 72
Reputation: 76194
total_years
is an integer and str(years_list[i])
is a string. You can't add a string to an integer.
When you use int
instead, you get IndexError because you're iterating way past the end of years_list
. The string representation of a list is typically much longer than the list's actual length. Ex. [1,2,3]
has a length of 3, but str([1,2,3])
has a length of 9 because it counts the commas and brackets and spaces. Maybe you meant to do for i in range(len(years_list))
.
You don't need any of this type-changing stuff anyway. If you want to add all the elements of a list, use sum
.
total_years = sum(years_list)
Upvotes: 1