Cover Image for int object is not iterable in Python
144 views

int object is not iterable in Python

The error message “int object is not iterable” in Python typically occurs when you attempt to iterate (loop over) an integer (int) object using a for loop or similar construct. Integers in Python are not iterable by default because they represent single, scalar values, not collections of items. To iterate over a range of integers or perform a loop a specific number of times, you should use functions or constructs that are designed for iteration.

Here are some common scenarios where you might encounter this error and how to address them:

  1. Iterating Over an Integer Directly:
   num = 5
   for item in num:  # Causes "int object is not iterable" error
       print(item)

To fix this, use a loop construct that expects an iterable, like range:

   num = 5
   for item in range(num):
       print(item)
  1. Using an Integer as an Iterable:
   num = 12345
   for digit in num:  # Causes "int object is not iterable" error
       print(digit)

To address this, convert the integer to a string and iterate over its characters:

   num = 12345
   for digit in str(num):
       print(digit)
  1. Attempting to Iterate Over a Non-Iterable Object:
   age = 25
   for element in age:  # Causes "int object is not iterable" error
       print(element)

In this case, you should reconsider the data type or data structure you are trying to iterate over, as integers are not suitable for this purpose.

In summary, the “int object is not iterable” error indicates that you are trying to loop over an integer, which is not a sequence or iterable object. To resolve the error, use the appropriate iteration constructs, such as range, or convert the integer to a suitable iterable type, like a string, depending on your specific use case.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS