'int' object is not iterable

10,549

Solution 1

Because you need to use range(len(s)) to get a list of integers to iterate over (or xrange in Python 2.x).

Alternatively, you can use enumerate():

for i, val in enumerate(s):
    print(i)
    print(val) # equivalent to s[i]

Or just not use an index in the first place:

for c in s:
    print(c)

Solution 2

You should do:

for i in xrange(len(s)):
Share:
10,549
rtwelve
Author by

rtwelve

Updated on September 04, 2022

Comments

  • rtwelve
    rtwelve over 1 year

    7.3 and was wondering about why in the following example the string "racecar" is being treated as type int. Thanks in advance for any help

    >>> s = "racecar"
    
    >>> for i in len(s):
    
        print(s[i]) 
    
    Traceback (most recent call last):
    
      File "<pyshell#9>", line 1, in <module>
    
        for i in len(s):
    
    TypeError: 'int' object is not iterable
    
    • Tadeck
      Tadeck almost 12 years
      It is not "string 'racecar'", it is "len(s)" that you want to iterate through. Result of "len(s)" is an int.
  • Karl Knechtel
    Karl Knechtel almost 12 years
    +1 for not using an index. Seriously, where did you get the idea that you would want or need to use an index? From another programming language, presumably. Python is better than that.
  • PM0087
    PM0087 almost 6 years
    Just quickly running it, I got this error: NameError: name 'xrange' is not defined
  • smichak
    smichak almost 6 years
    Sounds like you're in Python3. Try range instead of xrange.