Warm tip: This article is reproduced from stackoverflow.com, please click
python

TypeError: 'int' object is not iterable

发布于 2020-03-27 10:24:14

I have a list of lists that I want to iterate over for reasons later in the project. However, when I try to iterate over each list in the normal, pythonic way, I get an the error TypeError: 'int' object is not iterable. So, to test how the code was working I wrote

for i in self.features:
  print(i)
  print("Test1")

for i in len(self.features):
  print(i)
  print("Test2")

The program is successfully able to execute all the items in the Test1 loop, and none in the second. For the first test the output is:

Test1
2      169.091522
3      171.016678
4      170.381485
5      170.361954
6      170.322845
 ....
245    149.510544
246    145.642090
247    155.898438
248    154.886688
249    154.966034
Name: Adj Close, Length: 248, dtype: float64

So, features seems to be a list of lists, just like I had wanted, but it appears to not want to allow me to do the things you can typically do with a list.

To see the code in action, you can run it here https://repl.it/@JacksonEnnis/KNNFinalProduct

Questioner
Jackson Ennis
Viewed
17
Jim Wright 2019-07-03 22:48

len() returns the length of a list as an int. Python will be interpreting your code as:

for i in 5:
  print(i)
  print("Test2")

It will fail when interpreting the for statement and will never enter the loop.


To correctly iterate over the list your first snippet is correct.

for i in self.features:
  print(i)
  print("Test1")

If you wanted to iterate through a range of numbers up to the size of your list, you should use range().

for i in range(1, len(self.features) + 1):
  print(i)
  print("Test2")

As suggested by @PeterWood you could also use enumerate().

for i, _ in enumerate(self.features, 1):
  print(i)
  print("Test2")