Iterable vs Iterator in Python

Posted by Afsal on 07-Mar-2025

Python has two important concepts when it comes to looping over data: iterables and iterators. Though they seem similar, they are quite different. Understanding this difference is key to writing efficient Python code.

What is an Iterable?
An iterable is any object that can be looped over using a for loop. Examples of iterables include lists, tuples, strings, dictionaries, sets, and files.

Key characteristics of an iterable:
✅ It stores a collection of elements.
✅ It implements __iter__(), which returns an iterator.
✅ It does not track the current position in the iteration.

code

my_list = [1, 2, 3]  

for num in my_list:
    print(num)

Output

1
2
3

Here, my_list is an iterable, but not an iterator because it does not have a __next__() method.

What is an Iterator?
An iterator is an object that remembers its position and allows retrieving elements one by one using next().

Key characteristics of an iterator:
✅ It implements both __iter__() and __next__().
✅ It remembers its current position in iteration.
✅ It fetches elements lazily, meaning it doesn’t load all elements into memory at once.

You can create an iterator from an iterable using iter():

>>> my_list = [1, 2, 3]
>>> my_iter = iter(my_list)
>>> next(my_iter)
1
>>> next(my_iter)
2
>>> next(my_iter)
3
>>> next(my_iter)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration
>>> 

Here, my_iter is an iterator because it has a __next__() method.

Feature Iterable Iterator
Stores data? ✅ Yes ❌ No
Implements __iter__()? ✅ Yes ✅ Yes
Implements __next__()? ❌ No ✅ Yes
Can be reused? ✅ Yes ❌ No (Exhausts)
Examples List, tuple, string, dict File object, generator

When to Use What?
Use iterables when you need to store and access data multiple times.
Use iterators when you need to process data efficiently, especially for large datasets.

Hope you have learned something from this post. In the upcoming post we will learn how to write own custom iterator. Please share your valuable suggestions with afsal@parseltongue.co.in