Python/NumPy: How to Fix "TypeError: 'X' object is not iterable" (for int, numpy.int64, type)
The TypeError: 'X' object is not iterable
is a fundamental Python error that occurs when you attempt to use an object of type 'X' in a context that requires an iterable—that is, an object capable of returning its members one at a time. Common contexts include for
loops, membership tests (in
, not in
), and functions that expect a sequence of items (like sum()
, list()
, tuple()
). This error frequently appears with int
(standard Python integers), numpy.int64
(NumPy integers), and even type
objects if used incorrectly.
This guide will thoroughly explain why this TypeError
arises for these specific non-iterable types, demonstrate common scenarios that trigger it, and provide clear solutions, such as using range()
for integer iteration, ensuring you're operating on actual collections (like lists or NumPy arrays) rather than their scalar elements, and correctly calling built-in functions.
Understanding "Iterable" Objects and the TypeError
An iterable in Python is any object that can be looped over, meaning it can return its items one by one. Examples include:
- Sequences:
list
,tuple
,str
,range
objects. - Collections:
dict
(iterates over keys by default),set
. - NumPy arrays (
ndarray
). - File objects.
- Custom objects that implement the iteration protocol (
__iter__()
and__next__()
methods).
Objects that are not iterable typically represent single, atomic values. These include:
- Numbers:
int
,float
,complex
,numpy.int64
,numpy.float64
, etc. bool
(True
,False
).NoneType
(None
).type
objects themselves (e.g., the classlist
orrange
before being called).
The TypeError: 'X' object is not iterable
occurs when you try to use an object of type 'X' (which is not iterable) in an operation that requires an iterable, such as a for
loop or a function like sum()
.
Error Case 1: TypeError: 'int' object is not iterable
(Python's Standard Integer)
Cause: Attempting to Iterate Directly Over an int
A single integer value does not contain multiple items to loop through.
my_number = 5
try:
# ⛔️ TypeError: 'int' object is not iterable
for digit in my_number:
print(digit)
except TypeError as e:
print(f"Error (iterating int): {e}")
Output:
Error (iterating int): 'int' object is not iterable
Solution: Use range()
for Iterating a Number of Times
If you want to loop a certain number of times based on an integer, use the range()
function.
count_to_loop = 5
print("Iterating using range(count_to_loop):")
for i in range(count_to_loop): # Iterates 0, 1, 2, 3, 4
print(i)
Output:
Iterating using range(count_to_loop):
0
1
2
3
4
Cause: Passing an int
to Functions Expecting Iterables (e.g., sum()
, list()
)
Functions like sum()
, list()
, tuple()
, set()
, max()
, min()
expect an iterable as their main argument (or one of their arguments).
single_int = 10
try:
# ⛔️ TypeError: 'int' object is not iterable
total = sum(single_int) # sum() expects an iterable of numbers
except TypeError as e:
print(f"Error (summing int): {e}")
Output:
Error (summing int): 'int' object is not iterable
Solution: Wrap Integers in a List or Other Iterable
If you intend to operate on a single integer with these functions, or a collection of integers, ensure they are passed within an iterable.
import numpy as np
single_int = 10
int_val1 = 10
int_val2 = 20
# ✅ Pass a list of integers to sum()
total_sum = sum([int_val1, int_val2, 30])
print(f"Sum of [10, 20, 30]: {total_sum}") # Output: 60
# ✅ To create a list containing a single integer:
list_from_int = list([single_int]) # Note: list(10) would error, needs list([10])
print(f"List from single int: {list_from_int}") # Output: [10]
Output:
Sum of [10, 20, 30]: 60
List from single int: [10]
Cause: Using len()
in a for
loop (Iterating over an int
)
A common mistake is for i in len(my_sequence):
. len()
returns an integer (the length), which is not iterable.
my_string = "hello"
length_of_string = len(my_string) # This is 5 (an int)
try:
# ⛔️ TypeError: 'int' object is not iterable
for i in length_of_string:
print(i)
except TypeError as e:
print(f"Error (iterating len()): {e}")
Output:
Error (iterating len()): 'int' object is not iterable
Solution: Use range(len(my_sequence))
as shown in 2.2, or iterate directly over the sequence: for char in my_string:
.
Error Case 2: TypeError: 'numpy.int64' object is not iterable
(NumPy Integer)
This is analogous to the Python int
error but occurs with NumPy's scalar integer types (like np.int64
, np.int32
).
Cause: Iterating Over a Scalar NumPy Integer
import numpy as np
numpy_scalar_int = np.int64(25)
try:
# ⛔️ TypeError: 'numpy.int64' object is not iterable
for digit_part in numpy_scalar_int:
print(digit_part)
except TypeError as e:
print(f"Error (iterating np.int64): {e}")
# This also happens if you extract a scalar from an array and try to iterate it:
my_np_array = np.array([10, 20, 30])
scalar_element = my_np_array[0] # scalar_element is np.int64(10)
try:
for item in scalar_element: # Iterating over np.int64(10)
print(item)
except TypeError as e:
print(f"Error (iterating np.int64 element): {e}")
Output:
Error (iterating np.int64): 'numpy.int64' object is not iterable
Error (iterating np.int64 element): 'numpy.int64' object is not iterable
Solution: Iterate Over a NumPy Array of Integers, or Use range()
- To iterate a number of times specified by a NumPy integer:
for i in range(numpy_scalar_int.item()):
(using.item()
to get Python int). - To iterate over elements of a NumPy array:
for element in my_np_array:
.
Cause: Passing a NumPy Scalar Integer to Functions Expecting Iterables
Similar to Python int
s.
import numpy as np
np_int1 = np.int64(50)
np_int2 = np.int64(75)
try:
# ⛔️ TypeError: 'numpy.int64' object is not iterable
total = sum(np_int1, np_int2) # sum() needs an iterable
except TypeError as e:
print(f"Error (summing np.int64): {e}")
Output:
Error (summing np.int64): 'numpy.int64' object is not iterable
Solution: Wrap NumPy Scalar in a List/Array or Operate on an Array
import numpy as np
np_int1 = np.int64(50)
np_int2 = np.int64(75)
# ✅ Pass a list of NumPy integers (or a NumPy array)
total_np_sum = sum([np_int1, np_int2])
print(f"Sum of [np.int64(50), np.int64(75)]: {total_np_sum}") # Output: 125
np_array_for_sum = np.array([np_int1, np_int2, np.int64(100)])
print(f"Sum of NumPy array: {sum(np_array_for_sum)}") # Output: 225
# Or use NumPy's sum: print(np.sum(np_array_for_sum))
Output:
Sum of [np.int64(50), np.int64(75)]: 125
Sum of NumPy array: 225
Error Case 3: TypeError: 'type' object is not iterable
(Python Type/Class Itself)
This error usually means you've referenced a type/class (like range
or a custom class) where an instance of that type (created by calling it, e.g., range(5)
) or an iterable object was expected.
Cause: Forgetting to Call a Callable Type (e.g., range
instead of range()
)
try:
# ⛔️ TypeError: 'type' object is not iterable
for i in range: # 'range' is the type/class, not an instance like range(5)
print(i)
except TypeError as e:
print(f"Error (iterating 'type' range): {e}")
Output:
Error (iterating 'type' range): 'type' object is not iterable
Solution: Call the Callable Type with Parentheses ()
print("Iterating using range(0, 3):")
for i in range(0, 3): # ✅ Correct: range(0,3) creates an iterable range object
print(i)
Output:
Iterating using range(0, 3):
0
1
2
Cause: Attempting to Iterate Over a Custom Class Type That Isn't Iterable
class MyDataContainer:
# This class is not inherently iterable
data_value = 100
try:
# ⛔️ TypeError: 'type' object is not iterable
for item in MyDataContainer: # Trying to iterate over the class itself
print(item)
except TypeError as e:
print(f"Error (iterating custom 'type'): {e}")
Output:
Error (iterating custom 'type'): 'type' object is not iterable
Solution: Make Custom Class Iterable (Implement __iter__
and __next__
)
If you intend for instances of your class (or the class itself, though less common for direct iteration) to be iterable, you need to implement the iteration protocol.
class IterableCounter:
def __init__(self, start, end):
self.current = start
self.end = end
def __iter__(self): # Makes instances iterable
return self
def __next__(self):
if self.current < self.end:
val = self.current
self.current += 1
return val
else:
raise StopIteration
print("Iterating over an instance of IterableCounter:")
for num_val in IterableCounter(1, 4): # Iterate over an instance
print(num_val) # Output: 1, 2, 3
Output:
Iterating over an instance of IterableCounter:
1
2
3
Error Case 4: TypeError: argument of type 'int' is not iterable
(Membership Test with in
)
This specific wording of the TypeError
often occurs when using the in
or not in
membership operators where the right-hand side (the container being checked) is an integer.
Cause: Using in
Operator with an Integer as the Right-Hand Operand
my_number_container = 15035
character_to_find = '3'
try:
# ⛔️ TypeError: argument of type 'int' is not iterable
if character_to_find in my_number_container:
print("Found")
except TypeError as e:
print(f"Error (membership test with int): {e}")
Output:
Error (membership test with int): argument of type 'int' is not iterable
The in
operator expects an iterable (like a string, list, tuple, set, dict keys) on its right side to check for membership. An int
is not.
Solution: Ensure Right-Hand Operand is Iterable (e.g., String, List)
If my_number_container
was supposed to be a string or list, fix its assignment.
Solution: Convert Integer to String for Character Membership Test
If you want to check if a digit (as a character) exists within the string representation of a number:
my_number_container = 15035
character_to_find = '3'
# ✅ Convert the number to a string before checking
if character_to_find in str(my_number_container):
print(f"'{character_to_find}' found in string representation of {my_number_container}.")
else:
print(f"'{character_to_find}' NOT found in string representation of {my_number_container}.")
Output:
'3' found in string representation of 15035.
General Debugging: Checking if an Object is Iterable
You can programmatically check if an object is iterable using a try-except
block with iter()
. The iter()
function raises a TypeError
if its argument is not iterable.
import numpy as np
def is_iterable(obj):
try:
iter(obj)
return True
except TypeError:
return False
print(f"Is 100 iterable? {is_iterable(100)}") # False
print(f"Is np.int64(5) iterable? {is_iterable(np.int64(5))}") # False
print(f"Is 'hello' iterable? {is_iterable('hello')}") # True
print(f"Is [1,2] iterable? {is_iterable([1,2])}") # True
print(f"Is np.array([1,2]) iterable? {is_iterable(np.array([1,2]))}") # True
print(f"Is type range iterable? {is_iterable(range)}") # False (the type itself)
print(f"Is range(5) iterable? {is_iterable(range(5))}") # True (an instance)
Output:
Is 100 iterable? False
Is np.int64(5) iterable? False
Is 'hello' iterable? True
Is [1,2] iterable? True
Is np.array([1,2]) iterable? True
Is type range iterable? False
Is range(5) iterable? True
Conclusion
The TypeError: 'X' object is not iterable
errors are fundamental to Python's type system and iteration protocol.
- Integers (
int
,numpy.int64
) are not iterable: Userange()
if you need to loop a number of times based on an integer. When passing to functions likesum()
orlist()
, ensure integers are part of an iterable collection (e.g., a list[my_int]
). - Type objects (
type
) are not iterable by default: If you see this withrange
orlist
, you likely forgot to call them (e.g.,range(5)
instead ofrange
). For custom classes, implement the iteration protocol (__iter__
,__next__
) if you want their instances to be iterable. - For membership tests (
in
): The right-hand operand must be an iterable. Convert integers to strings (str(my_int)
) if you're checking for digit characters.
By understanding what makes an object iterable and ensuring you provide iterables where Python expects them, you can avoid these common TypeError
s.