How do I fix an "'int' object is not iterable" error?
I’m working on the count problem, and have come up with the following code:
def count(sequence, item):
found = 0
for i in len(sequence):
if sequence[i] == item:
found = found + 1
return found
but when I submit it I get an “‘int’ object is not iterable” error. I’m not really sure whether that means there’s a problem with the variable found which is an integer, or if sequence isn’t being recognised as a list…or some other possibility I haven’t thought of.
Can anyone explain what that error message means and how I should fix it?
Answer 54f2371095e378e4ea002ede
The error is that here, you need to use i
to iterate through a list, but you specified an integer, namely len(sequence)
, instead of the necessary list …
for i in len(sequence):
To iterate through all integers from 0
up to, but not including len(sequence)
, you can specify the needed list, as follows …
for i in range(len(sequence)):
1 comments
Aha, thank you! I was thinking of the range initially but didn’t realise I hadn’t actually written it in.
Popular free courses
- Free course
Learn SQL
In this SQL course, you'll learn how to manage large datasets and analyze real data using the standard data management language.Beginner Friendly4 Lessons - Free course
Learn JavaScript
Learn how to use JavaScript — a powerful and flexible programming language for adding website interactivity.Beginner Friendly11 Lessons - Free course
Learn HTML
Start at the beginning by learning HTML basics — an important foundation for building and editing web pages.Beginner Friendly6 Lessons