Last updated: Apr 8, 2024
Reading timeยท3 min
To check if an object is iterable in Python:
iter()
function.iter
function raises a TypeError
if the passed-in object is not
iterable.TypeError
using a try/except
statement.my_str = 'hello' try: my_iterator = iter(my_str) print('The object is iterable') for i in my_iterator: print(i) # ๐๏ธ h, e, l, l, o except TypeError as te: print('The object is NOT iteralbe')
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 you have to do this often, define a reusable function.
def is_iterable(value): try: iter(value) return True except TypeError: return False print(is_iterable('hello')) # ๐๏ธ True print(is_iterable(100)) # ๐๏ธ False my_str = 'hello' if is_iterable(my_str): print('The value is iteralbe') else: print('The value is not iterable')
The is_iterable
function takes a value and returns True
if the value is
iterable and False
otherwise.
iter()
function raises an errorIf we pass a non-iterable object like an integer to the iter()
function, the
except
block is run.
my_int = 100 try: my_iterator = iter(my_int) print('The object is iterable') for i in my_iterator: print(i) except TypeError as te: # ๐๏ธ This runs print('The object is NOT iterable') print(te) # ๐๏ธ 'int' object is not iterable
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.
iter(obj)
.Other options are not as complete. For example, you can use the Iterable
class
from the collections.abc
module.
from collections.abc import Iterable my_list = ['a', 'b', 'c'] print(isinstance(my_list, Iterable)) # ๐๏ธ True print(isinstance(100, Iterable)) # ๐๏ธ False if isinstance(my_list, Iterable): # ๐๏ธ This runs print('The object is iterable') else: print('The object is NOT iterable')
Make sure to import the Iterable
class before using it.
The
collections.abc.Iterable
class enables us to check if another class is registered as Iterable
or has an
__iter__()
method.
However, it doesn't detect classes that iterate with the __getitem__()
method.
This is why the most reliable way to check if an object is iterable is to pass
the object to the iter()
built-in function.
The iter()
function raises a TypeError
if the passed-in value doesn't
support the __iter__()
method or the sequence protocol (the __getitem__()
method).
__iter__
methodHaving considered that, most of the built-in objects that are iterable implement
the __iter__()
method.
print({}.__iter__) print(().__iter__) print([].__iter__) print(''.__iter__) print({'a', }.__iter__)
You can either try to access the method as an attribute to see if the object has
it or print the object's attributes with the dir()
function, e.g.
print(dir(my_object))
and check if it has an __iter__
attribute.
__iter__
methodHere is an example of how to make a class iterable by implementing 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.
You can learn more about the related topics by checking out the following tutorials: