TypeError: 'int' object is not iterable in Python

TypeError: 'int' object is not iterable in Python

posted 11 min read

Updated on: 2023-10-29

The exception [1] or error message "TypeError: 'int' object is not iterable" tells us that we did something wrong — trying to iterate on an int or integer object. TypeError [2] is an exception, when an operation is applied to a data type that is not supported. This operation typically happens when we use a "for statement" to get the members of an object which is fine for a list, tuple, dict and others but not for integer. Integer is a whole number, it is not a container to store data members.

We can only iterate on objects such as list, tuple, str, and other iterables. In this article, I will discuss these iterables [3] and suggest how to avoid this error.

1.  What is this error? #

The issue that may arise from our code is the error message TypeError: 'int' object is not iterable raised by Python, telling us that we tried to iterate on an integer object. No, we cannot iterate on an integer, but we can on other data types like list, str, tuple, dict, and others.

An integer is a whole number and does not contain any members, while the iterable list may contain members where one can iterate, with the use of "for statement" and others.

Let's have an example code to reproduce the error message.

code

# Define an int or integer variable.
num_sports = 1000

# Let's try to iterate and print the members of num_sports.
for value in num_sports:
    print(value)

output

Traceback (most recent call last):
  File "F:\Project\coderlegion\a.py", line 5, in <module>
    for value in num_sports:
TypeError: 'int' object is not iterable

All right we successfully reproduce the exception type "TypeError" and the message "'int' object is not iterable".

1.1.  Integers #

An int or integer is just a data type or object that can have a value of 0 or a positive and negative whole number.

Here are some examples of an integer data type.

my_best_error = 0
grade = 85
temperature = -5

1.2.  Iterables #

According to python documentation, iterables [3] are objects that are capable of returning their members one at a time. Examples of iterables include all sequence types such as (list, str, and tuple) and some non-sequence types such as dictionary, etc.

Here are some examples of iterables.

code

# Sample iterables
countries = ['Australia', 'Philippines', 'China']  # a list of str
dog_name = 'Jupiter'  # an str
favorite_fruits = ('Avocado', 'Pineapple', 'Mango')  # a tuple of str
typhoon_speed_kph = [75, 125, 245]  # a list of int
beautiful_cities = {'Amsterdam': 'Netherlands', 'Barcelona': 'Spain'}  # a dict of str: str

Here is an example of how to iterate the values of a list iterable.

code

# Define our iterable list of str.
countries = ['Australia', 'Philippines', 'China']
   
# Print the values of our iterable.
for value in countries:
    print(value)

output

Australia
Philippines
China
FAQ How do we know if a variable or object is iterable or not? Answer: We can use the built-in function dir(object), and see if there is attribute __iter__ on it. Or we can use the built-in function hasattr(). Or use the try and except statement and catch the TypeError exception.

Python has a built-in function called dir(object) that can access the attribute of an object. If an iter attribute is present then this object is iterable. Here is an example code on how to use dir() and iter.

code

num_golds = 40
if '__iter__' in dir(num_golds):
    print('This is iterable.')
else:
    print('This is not iterable.')

output

This is not iterable.

Here is an example code on how to know if an object is iterable or not using the hasattr() [4]. If the object does not have an iter attribute then it is not an iterable otherwise it is an iterable.

code

num_trees = 1000
print(hasattr(num_trees, '__iter__'))

output

False

code

list_trees = [100, 200, 1000]
print(hasattr(list_trees, '__iter__'))

output

True

2.  How to avoid this error? #

To avoid this issue, we must not iterate on an integer variable or object because python does not support it and never will.

Programmatically, and avoid program flow interruption, we can use the "try and except" statement and use the "for statement" [5] or use the built-in functions len() [6] or iter() to capture the TypeError exception thrown. We can also use our custom function is_iterable(). We can also use the built-in function hasattr(). Let's try all of those with example codes.

2.1.  The try and except statement #

Let's presume we don't know the object type, and that we want to print the elements of the object. We can use the "try and except" statement so that the flow of our program is not interrupted. If we encounter the TypeError, we just pass on it and continue with the next statement.

2.1.1.  The for statement #

code

# Define our supposedly iterable object.
our_object = 100

# Print this quote at the end with or without an error.
life_quote = 'Life is beautiful!'

# Let's try to iterate on the elements of our iterable and print it.
try:
    for value in our_object:
        print(value)
except TypeError:
    pass  # no operation to be made, continue on the next statement

# next statement
print(life_quote)

output

Life is beautiful!

Look, the flow of our program was not interrupted by the TypeError. We successfully printed the life_quote variable value.

Let's consider another example, this time we will use a valid iterable.

code

# Define our supposedly iterable object.
our_object = ('Avocado', 'Pineapple', 'Mango')

# Print this quote at the end with or without an error.
life_quote = 'Life is beautiful!'

# Let's try to iterate on the elements of our iterable and print it.
try:
    for value in our_object:
        print(value)
except TypeError:
    pass  # no operation to be made, continue on the next statement

# next statement
print(life_quote)

output

Avocado
Pineapple
Mango
Life is beautiful!

We successfully printed the elements of our iterable as well as the life_quote value.

2.1.2.  The built-in function len() #

Instead of using the "for statement", we can also use the built-in len() [6] function to determine if an object is iterable.

Here is an example code trying to determine if an integer object is iterable or not.

code

# Define our object.
ships = 4

# Try to get the number of elements of ships.
try:
    num_ships_length = len(ships)
except TypeError:
    print('The object passed to len is not iterable.')
else:
    # If there is no exception.
    print('The object passed to len is iterable.')

output

The object passed to len is not iterable.

Let's try a valid iterable and use len() [6] on it.

code

# Define our object.
ships = ['The Mayflower', 'Battleship USS Arizona', 'Titanic']

# Try to get the number of elements of ships.
try:
    num_ships_length = len(ships)
except TypeError:
    print('The object passed to len is not iterable.')
else:
    # If there is no exception.
    print('The object passed to len is iterable.')

    # Print the items.
    for value in ships:
        print(value)

output

The object passed to len is iterable.
The Mayflower
Battleship USS Arizona
Titanic

We did not encounter the error because a valid iterable has a length or number of items.

2.1.3.  The built-in function iter() #

Instead of for and len(), we can also use the built-in iter() [7] to try to convert an object into an iterator. If it throws a TypeError exception, that would mean the object is not iterable.

code

# Define our object.
planets = 100

# Try to convert planets into an iterator.
try:
    iter_object = iter(planets)
except TypeError:
    print(f'The object passed to iter is not iterable.')
else:
    # When we reach here, the try is successful.
    print(f'The object passed to iter is iterable.')

    # Print all the members of the object.
    for p in iter_object:
        print(p)

output

The object passed to iter is not iterable.

Let's input a valid iterable.

code

# Define our object.
planets = ['Earth', 'Mars', 'Jupiter']

# Try to convert planets into an iterator.
try:
    iter_object = iter(planets)
except TypeError:
    print(f'The object passed to iter is not iterable.')
else:
    # When we reach here, the try is successful.
    print(f'The object passed to iter is iterable.')

    # Print all the members of the object.
    for p in iter_object:
        print(p)

output

The object passed to iter is iterable.
Earth
Mars
Jupiter

2.2.  Our custom function is_iterable() #

Here is an example program using our custom function is_iterable(). This technique does not use the "try and except" statement.

Note The is_iterable() function is backed by the built-in function dir(object) and it checks the presence of the __iter__ attribute of the object.

code

def is_iterable(object):
    """
    Check if an object is iterable or not.

    It uses the built-in function dir(object) to return the
    object's attributes. If there is __iter__ attribute then
    this object is iterable.

    Args:
      object: The variable or object to check.

    Returns:
      True if object is an iterable, False if not.
    """
    return True if '__iter__' in dir(object) else False

def show_iterable_members(object):
    is_iter = is_iterable(object)
    if is_iter:
        print(f'The object type is {type(object)} and it is iterable.')

        # Check if the object is a dict, as we will print the key and value.
        if isinstance(object, dict):
            for key, value in object.items():
                print(f'key: {key}, value: {value}')
        # Else just print the value.
        else:
            for value in object:
                print(value)
    else:
        print(f'The object type is {type(object)} and it is not iterable.')

if __name__ == '__main__':
    # Define an integer object.
    num_covid_cases = 900000  # int
    show_iterable_members(num_covid_cases)

    print()
    appliances = {0: 'Electric fan', 1: 'oven'}  # a dict of int:str
    show_iterable_members(appliances)

    print()
    oceans = ['Indian', 'Pacific', 'Atlantic']  # a list of str
    show_iterable_members(oceans)

    print()
    fiba_ranking = (('USA', 761), ('ESP', 759), ('AUS', 741))  # a tuple of tuples
    show_iterable_members(fiba_ranking)

output

The object type is <class 'int'> and it is not iterable.

The object type is <class 'dict'> and it is iterable.
key: 0, value: Electric fan
key: 1, value: oven

The object type is <class 'list'> and it is iterable.
Indian
Pacific
Atlantic

The object type is <class 'tuple'> and it is iterable.
('USA', 761)
('ESP', 759)
('AUS', 741)

2.3.  The built-in function hasattr() #

Here is a sample code on how to avoid the error using the built-in function hasattr().

code

# Define our supposedly iterable object.
object = 100

# Use the built-in function hasattr to determine if our object is iterable.
if hasattr(object, '__iter__'):
    print('The object is iterable.')
    for value in object:
        print(value)
else:
    print('The object is not iterable.')

output

The object is not iterable.

We can replace the value of an object to a list like [1, 9, 14], and it will print "The object is iterable." along with the values 1, 9, and 14.

3.  Conclusion

The int or integer data type is not an iterable object. It is a whole number like 100, it has no members that someone can iterate around. An iterable is an object that has members or elements. Examples of iterable objects are list, tuple, str, and others. If we try to get the values of an object with a for statement [5], and this object is an int then we would get the TypeError: 'int' object is not iterable exception or error message.

We can avoid this error by checking if the object that we are going to process is iterable or not, with the use of "try and except", hasattr, and others.

4.  References

If you read this far, tweet to the author to show them you care. Tweet a Thanks

More Posts

Typeerror: 'webelement' object is not iterable

MostafaTava - Mar 6

TypeError: 'Builtin_function_or_method' object is not subscriptable python

Muhammad Sameer Khan - Jan 28

How to Fix the TypeError: cannot use a string pattern on a bytes-like object Error in Python

Cornel Chirchir - Oct 29, 2023

NameError: name 'pd' is not defined in Python [Solved]

muhammaduzairrazaq - Feb 29

Numpy.ndarray' object is not callable Error: Fixed

Muhammad Sameer Khan - Nov 15, 2023
chevron_left