'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)):
Author by
rtwelve
Updated on September 04, 2022Comments
-
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 almost 12 yearsIt is not "string '
racecar
'", it is "len(s)
" that you want to iterate through. Result of "len(s)
" is anint
.
-
-
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 almost 6 yearsJust quickly running it, I got this error:
NameError: name 'xrange' is not defined
-
smichak almost 6 yearsSounds like you're in Python3. Try range instead of xrange.