Python TypeError: int object is not iterable: What To Do To Fix It? (2024)

Are you seeing the error “TypeError ‘int’ object is not iterable” while running a Python program? This tutorial will show you how to fix it.

Python raises the TypeError ‘int’ object is not iterable when you try to access a variable of type integer as an iterable. One scenario in which this might happen is if by mistake you try to iterate through an integer variable using a for loop when you actually expect it to be an iterable (e.g. a list, tuple, or set).

I will show you an example of code that causes this error and then we will fix it together!

You will also learn how to troubleshoot a more complex example at the end of the article.

What Does the Python TypeError “int object is not iterable” Mean?

An iterable in Python is an object you can iterate through. Some examples of iterables are lists, tuples, and sets.

The most common way to iterate through an iterable is by using a Python for loop, but sometimes this can lead to a TypeError due to mistakes in the code.

Let’s have a look at the following Python code:

numbers = [3, 56, 78, 65, 5, 3]for number in len(numbers): print(number)

If you look at this code quickly you might not see any errors straight away.

When executing the code you will see the following error:

Traceback (most recent call last): File "/opt/codefathertech/tutorials/list_iterator.py", line 3, in <module> for number in len(numbers):TypeError: 'int' object is not iterable

Why this error message?

The cause of this error is the fact that we are using a for loop to iterate through the variable with value len(numbers) and this variable is an integer that contains the number of elements in the list numbers.

The initial intent of the code was to loop through each element in the list and if we wrote the code correctly it would work as expected because a list is an iterable.

What change do you have to make to the code to make it work?

To fix the TypeError “int object is not iterable” use the range function on the first line of the for loop.

for number in len(numbers):

becomes:

for number in range(len(numbers)):

Let’s have a look at the updated code:

numbers = [3, 56, 78, 65, 5, 3]for number in range(len(numbers)): print(number)

Execute the code to confirm that you stop seeing the TypeError and that all the numbers in the list are printed in the output correctly.

012345

All good! You fixed this error.

Note: the code that is raising this exception in your case might be slightly different from the example we have seen. The main point is for you to check if by mistake you are trying to loop through an integer.

How Can You Make an Integer Value Iterable in Python?

An integer represents a single value and it’s conceptually incorrect trying to loop over it. Integers are not iterable.

It doesn’t really make sense to make an integer iterable considering that an iterable is a Python object that contains multiple objects (e.g. a list that contains multiple strings you can loop through).

How Do You Check if an Object is Iterable in Python?

An iterable object in Python implements the method __iter__() so a simple way to check if an object is an iterable is to verify if the object has the method __iter__().

Let’s take as an example one list and one integer to show how the first implements the __iter__() method while the second one doesn’t.

To verify if the __iter__() method is present in the object you can use the built-in function hasattr().

Checking if a list is iterable

numbers = [3, 56, 78, 65, 5, 3]if hasattr(numbers, '__iter__'): print("This object is iterable")else: print("This object is not iterable")[output]This object is iterable

This code confirms that a list is iterable.

Using the Python dir() function you can also see that this list has the method __iter__():

numbers = [3, 56, 78, 65, 5, 3]print(dir(numbers))[output]['__add__', '__class__', '__class_getitem__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getstate__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']

Checking if an integer is iterable

number = 3if hasattr(number, '__iter__'): print("This object is iterable")else: print("This object is not iterable")[output]This object is not iterable

By calling the dir() function you can also see that an integer does not have the method __iter__():

number = 3print(dir(number))[output]['__abs__', '__add__', '__and__', '__bool__', '__ceil__', '__class__', '__delattr__', '__dir__', '__divmod__', '__doc__', '__eq__', '__float__', '__floor__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__getnewargs__', '__getstate__', '__gt__', '__hash__', '__index__', '__init__', '__init_subclass__', '__int__', '__invert__', '__le__', '__lshift__', '__lt__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__round__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', '__xor__', 'as_integer_ratio', 'bit_count', 'bit_length', 'conjugate', 'denominator', 'from_bytes', 'imag', 'numerator', 'real', 'to_bytes']

Go through the output of the dir() function in both cases and make sure you understand the difference (the __iter__() method is only present in a list and not in an integer).

Example on How to Fix TypeError: int object is not iterable

Conceptually you now know why this exception is raised in Python.

At the same time, depending on the complexity of the code, it might be a bit harder to understand the root cause of the error.

Let’s take as an example the following code that is supposed to increase each number in a matrix by one and then print all the numbers in the matrix.

matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]for row in matrix: for column in range(len(row)): matrix[column] += 1print(matrix)

From a first look, this code might seem correct.

So, let’s try to execute it:

Traceback (most recent call last): File "/opt/codefathertech/tutorials/list_iterator.py", line 5, in <module> matrix[column] += 1TypeError: 'int' object is not iterable

The TypeError is complaining about the following line of code:

matrix[column] += 1

But why?

That’s because when using the += operator with a list you also need a list on the right side of the operator while in this code on the right side of the operator, we have an integer.

Also, the real problem here is that we have a conceptual bug in the code considering that the original intention of this code is to increment each number in the matrix by 1.

Let’s update our code to do that:

matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]for row in matrix: for column in range(len(row)): row[column] += 1print(matrix)

And the output is:

[[2, 3, 4], [5, 6, 7], [8, 9, 10]]

That’s correct!

Conclusion

In this Python tutorial, you learned to troubleshoot the error “TypeError: ‘int’ object is not iterable” and to identify which part of the code causes it.

We went through a few examples including a more complex one that shows that sometimes is not always easy to understand why this error occurs and how to fix it.

By practicing your Python coding you will find it easier to identify and address this type of error.

Related article: would you like to feel more confident about your Python knowledge? Start building a strong Python foundation withthis Python specialization.

Python TypeError: int object is not iterable: What To Do To Fix It? (1)

Claudio Sabato

Claudio Sabato is an IT expert with over 15 years of professional experience in Python programming, Linux Systems Administration, Bash programming, and IT Systems Design. He isa professional certified by the Linux Professional Institute.

With a Master’s degree in Computer Science, he has a strong foundation in Software Engineering and a passion for robotics with Raspberry Pi.

Related posts:

  1. Python Error: Name Is Not Defined. Let’s Fix It
  2. Why am I getting the Python error “Too Many Values To Unpack”?
  3. Python TypeError: list object is not an iterator – Let’s Fix It!
  4. Fix Python Error “List Indices Must Be Integers or Slices, Not Tuple”
Python TypeError: int object is not iterable: What To Do To Fix It? (2024)

References

Top Articles
7x De leukste kookworkshops in ’s-Hertogenbosch
10 x De Leukste Kinderuitjes In En Rondom ’s Hertogenbosch
No Hard Feelings (2023) Tickets & Showtimes
Canary im Test: Ein All-in-One Überwachungssystem? - HouseControllers
Belle Meade Barbershop | Uncle Classic Barbershop | Nashville Barbers
Byrn Funeral Home Mayfield Kentucky Obituaries
Klustron 9
Mawal Gameroom Download
Imbigswoo
Our History | Lilly Grove Missionary Baptist Church - Houston, TX
Encore Atlanta Cheer Competition
Maxpreps Field Hockey
Best Pawn Shops Near Me
Theycallmemissblue
6th gen chevy camaro forumCamaro ZL1 Z28 SS LT Camaro forums, news, blog, reviews, wallpapers, pricing – Camaro5.com
WWE-Heldin Nikki A.S.H. verzückt Fans und Kollegen
Seattle Rpz
Most McDonald's by Country 2024
Finger Lakes Ny Craigslist
Simpsons Tapped Out Road To Riches
Michigan cannot fire coach Sherrone Moore for cause for known NCAA violations in sign-stealing case
Walgreens San Pedro And Hildebrand
Mission Impossible 7 Showtimes Near Marcus Parkwood Cinema
UPS Store #5038, The
Catherine Christiane Cruz
Doublelist Paducah Ky
Winco Employee Handbook 2022
Chamberlain College of Nursing | Tuition & Acceptance Rates 2024
Lovindabooty
South Florida residents must earn more than $100,000 to avoid being 'rent burdened'
Wcostream Attack On Titan
Mg Char Grill
Shaman's Path Puzzle
Poster & 1600 Autocollants créatifs | Activité facile et ludique | Poppik Stickers
Desirulez.tv
Moxfield Deck Builder
No Hard Feelings Showtimes Near Tilton Square Theatre
Muziq Najm
Dadeclerk
2008 DODGE RAM diesel for sale - Gladstone, OR - craigslist
Oriellys Tooele
Metro Pcs Forest City Iowa
Beaufort SC Mugshots
Ezpawn Online Payment
Homeloanserv Account Login
'The Nun II' Ending Explained: Does the Immortal Valak Die This Time?
Unit 11 Homework 3 Area Of Composite Figures
Walmart Listings Near Me
Craigslist Free Cats Near Me
Ingersoll Greenwood Funeral Home Obituaries
Provincial Freeman (Toronto and Chatham, ON: Mary Ann Shadd Cary (October 9, 1823 – June 5, 1893)), November 3, 1855, p. 1
Tenichtop
Latest Posts
Article information

Author: Duane Harber

Last Updated:

Views: 5352

Rating: 4 / 5 (71 voted)

Reviews: 86% of readers found this page helpful

Author information

Name: Duane Harber

Birthday: 1999-10-17

Address: Apt. 404 9899 Magnolia Roads, Port Royceville, ID 78186

Phone: +186911129794335

Job: Human Hospitality Planner

Hobby: Listening to music, Orienteering, Knapping, Dance, Mountain biking, Fishing, Pottery

Introduction: My name is Duane Harber, I am a modern, clever, handsome, fair, agreeable, inexpensive, beautiful person who loves writing and wants to share my knowledge and understanding with you.