TypeError: Argument of Type ‘int’ is not Iterable

TypeError: Argument of Type ‘int’ is not Iterable

So you’re getting the TypeError: argument of type ‘int’ is not iterable error message. I came across this issue when calling an api, extracting some data from a json object, and trying to determine if I needed to do something with that info.

Bite Size Soln for Those in a Rush

In short, you’re trying to find whether a substring exists in an integer. Make sure to cast your ints to strings and you should be able to continue on your way. Now, if you’d like a more detailed explanation, continue on.

My Setup

Python 3.x
macOS

Are you having issues with Python locally? This article might help you out.

The Issue

You are inadvertently trying to determine if a substring is in an integer! Let’s recreate it in a line or two.

word = 'stuff'
blur = 12344566
word in blur

You should be greeted with the ugly, “TypeError: argument of type ‘int’ is not iterable” message.

The Solution

Cast, Cast, Cast.

word = 'stuff'
blur = 12344566
word in str(blur)

A More Realistic Example

This will output false successfully telling you whether stuff can be found within the now string ‘12344566’. And now for a more realistic example.

array = ['Foo','Bar', 1]
for element in array:
    print(element)
    if 'sandwich' in element:
        print('Found the sandwich') 

Here we can see all elements of the array are printed because the error occurs on the third element. One will never find a string in an int. You can avoid checking types and error handling by wrapping element in str() to cast it as a string in case we come across any unruly data types.

array = ['Foo','Bar', 1]
for element in array:
    print(element)
    if 'sandwich' in str(element):
        print('Found the sandwich') 

The problem is gone. We also never find the sandwich. Happy coding!

Leave a Comment