Profile image of InkLit
Submitted by InkLit
about 10 years

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

0 votes

Permalink

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)):
Profile image of AppylPye
Submitted by AppylPye
about 10 years

1 comments

Profile image of InkLit
Submitted by InkLit
about 10 years

Aha, thank you! I was thinking of the range initially but didn’t realise I hadn’t actually written it in.