Borislav Hadzhiev
Last updated: Apr 20, 2022
Check out my new book
The Python "TypeError: 'type' object is not iterable" occurs when we try to
iterate over a class that is not iterable, e.g. forget to call the range()
function. To solve the error, make the class iterable by implementing the
__iter__()
method.
Here is an example of how the error occurs when the range
function.
# ⛔️ TypeError: 'type' object is not iterable for i in range: print(i)
If you use the range
function, make sure to call it.
for i in range(0, 3): # 👉️ 0, 1, 2 print(i)
The range class is
commonly used for looping a specific number of times in for
loops and takes
the following parameters:
Name | Description |
---|---|
start | An integer representing the start of the range (defaults to 0 ) |
stop | Go up to, but not including the provided integer |
step | Range will consist of every N numbers from start to stop (defaults to 1 ) |
If you only pass a single argument to the range()
constructor, it is
considered to be the value for the stop
parameter.
start
and stop
parameters are provided, the start
value is inclusive, whereas the stop
value is exclusive.You will also get the error if you try to iterate over a class that doesn't
implement the __iter__()
method.
class Counter: pass # ⛔️ TypeError: 'type' object is not iterable for c in Counter: print(c)
If you need to make the class iterable, implement the __iter__
method.
class Counter: def __init__(self, start, stop): self.current = start - 1 self.stop = stop def __iter__(self): return self def __next__(self): self.current += 1 if self.current < self.stop: return self.current raise StopIteration for c in Counter(0, 4): print(c) # 👉️ 0, 1, 2, 3
The __iter__()
method is implicitly called at the start of loops and returns
the iterator object.
The __next__()
method is implicitly called at each loop increment and returns
the next value.
If you need to check if an object is iterable, use a try/except
statement.
my_str = 'hello' try: my_iterator = iter(my_str) for i in my_iterator: print(i) # 👉️ h, e, l, l, o except TypeError as te: print(te)
The iter() function
raises a TypeError
if the passed in value doesn't support the __iter__()
method or the sequence protocol (the __getitem__()
method).
If we pass a non-iterable object like a class to the iter()
function, the
except
block is ran.
Examples of iterables include all sequence types (list
, str
, tuple
) and
some non-sequence types like dict
, file objects and other objects that define
an __iter__()
or a __getitem__()
method.