why int object is not iterable while str is into python
Categories:
Why Python's int
is Not Iterable, but str
Is

Explore the fundamental differences in how Python handles integers and strings, clarifying why one is iterable and the other is not, with practical examples and conceptual insights.
In Python, you might have encountered situations where you can loop through a string character by character, but attempting to do the same with an integer results in a TypeError
. This behavior is fundamental to how Python defines and implements iterables. Understanding this distinction is crucial for writing correct and efficient Python code. This article will delve into the core concepts of iterability, how Python defines it, and why str
objects conform to this definition while int
objects do not.
Understanding Iterables in Python
An iterable in Python is an object that can return an iterator. An iterator is an object that defines the __iter__()
method, which returns itself, and the __next__()
method, which returns the next item from the sequence. When you use a for
loop, Python implicitly calls iter()
on the object, which in turn calls the object's __iter__()
method to get an iterator. Then, it repeatedly calls next()
on that iterator until a StopIteration
exception is raised, signaling the end of the sequence.
flowchart TD A[for item in iterable:] --> B{Call iter(iterable)} B --> C[Get iterator object] C --> D{Call next(iterator)} D --> E[Process item] E --> D D -- StopIteration --> F[End loop]
The Python iteration protocol workflow
Why Strings Are Iterable
Strings (str
) in Python are sequences of characters. Each character within a string can be accessed individually by its index, and the string itself has a defined length. This sequential nature makes strings inherently iterable. When you iterate over a string, Python provides an iterator that yields each character one by one, from left to right, until all characters have been consumed.
my_string = "Python"
for char in my_string:
print(char)
# Output:
# P
# y
# t
# h
# o
# n
Iterating over a string in Python
iter()
and then manually retrieve elements using next()
to understand the iteration protocol better.my_string = "abc"
string_iterator = iter(my_string)
print(next(string_iterator)) # Output: a
print(next(string_iterator)) # Output: b
print(next(string_iterator)) # Output: c
# print(next(string_iterator)) # This would raise StopIteration
Manual iteration using iter()
and next()
Why Integers Are Not Iterable
Integers (int
) in Python represent single, atomic numerical values. They do not have a sequence of sub-elements that can be iterated over. An integer, like 123
, is not composed of '1', '2', and '3' in the same way a string "123"
is composed of characters. From Python's perspective, an integer is a single, indivisible unit. Therefore, it does not implement the __iter__()
method, and attempting to iterate over it directly leads to a TypeError
.
my_integer = 123
try:
for digit in my_integer:
print(digit)
except TypeError as e:
print(f"Error: {e}")
# Output:
# Error: 'int' object is not iterable
Attempting to iterate over an integer results in a TypeError
int
directly, you can convert it to a str
if you need to process its digits individually. This is a common workaround.my_integer = 123
# Convert to string to iterate over digits
for digit_char in str(my_integer):
print(digit_char)
# Output:
# 1
# 2
# 3
Converting an integer to a string to iterate over its digits
The __iter__
and __next__
Methods
The presence or absence of the __iter__
method is the technical reason behind an object's iterability. Objects that implement __iter__
are iterables. Objects that implement both __iter__
and __next__
are iterators (and thus also iterables). Strings implement __iter__
, returning a string iterator. Integers do not implement __iter__
, hence they are not iterable.
classDiagram class Iterable { <<interface>> +__iter__() } class Iterator { <<interface>> +__iter__() +__next__() } class str { +__iter__() +__getitem__(index) ... } class int { -No __iter__() -No __next__() ... } Iterable <|-- str Iterator <|-- StringIterator str ..> StringIterator : creates
Class diagram showing iterability of str
vs. int
In summary, the distinction between int
and str
regarding iterability boils down to their fundamental data models in Python. Strings are designed as sequences of characters, making them naturally iterable, while integers are atomic numerical values without internal sequential components. This design choice reflects their distinct purposes and how they are intended to be used within the language.