Last modified: Apr 09, 2025 By Alexander Williams
Fix TypeError: 'int' object is not iterable
Python developers often encounter the error TypeError: 'int' object is not iterable. This happens when trying to loop over an integer. This article explains why it occurs and how to fix it.
Table Of Contents
What Causes This Error?
The error occurs when you try to iterate over an integer using a loop or function like for
or sum()
. Integers are not iterable in Python.
Only objects like lists, tuples, or strings can be iterated. Trying to loop over a number raises this error.
Common Scenarios
Here are common cases where this error appears:
1. Using a For Loop on an Integer
# Wrong code
num = 10
for i in num:
print(i)
TypeError: 'int' object is not iterable
2. Passing Integer to sum()
# Wrong code
total = sum(5)
TypeError: 'int' object is not iterable
How To Fix The Error
Here are solutions for each scenario:
1. Convert Integer to Iterable
Wrap the integer in a list or tuple to make it iterable.
# Fixed code
num = 10
for i in [num]: # Now it's a list
print(i)
2. Use range() For Loops
For looping over numbers, use range()
instead.
# Fixed code
for i in range(10): # Creates iterable range
print(i)
3. Check Variable Types
Use type()
to verify you're working with the right data type.
num = 10
print(type(num)) # Output:
Preventing The Error
Follow these best practices to avoid this error:
1. Always check variable types before iteration.
2. Use proper data structures for your needs.
3. Test code with different inputs.
For similar Python errors, see our guide on How To Solve ModuleNotFoundError.
Conclusion
The TypeError: 'int' object is not iterable is easy to fix once you understand it. Remember that only iterable objects can be looped over. Convert integers to lists or use range()
when needed.
Always verify your data types and test your code thoroughly. This will help you avoid similar errors in your Python projects.