Iterables in Python (62/100 Days of Python)
Iterables are one of the most important concepts in Python. An iterable is any object in Python that can be looped over. In other words, an iterable is a collection of objects that can be iterated over using a loop, such as a for
loop.
What are Iterables?
In Python, an iterable is any object that can be looped over using a for loop. Examples of iterables in Python include lists, tuples, sets, and dictionaries. These objects are iterable because they contain a collection of items that can be accessed one at a time using a loop.
numbers = [1, 2, 3, 4, 5]
for number in numbers:
print(number)
In this example, the numbers
list is an iterable, and we are using a for loop to iterate over each item in the list and print it to the console.
How Iterables Work in Python
When you use a for loop to iterate over an iterable in Python, the loop actually creates an iterator object behind the scenes. This iterator object is responsible for keeping track of the current item in the iterable and returning the next item each time the loop runs. Here is an example of how the for loop and iterator work together to iterate over a list:
numbers = [1, 2, 3, 4, 5]
iterator = iter(numbers)
while True:
try:
number = next(iterator)
print(number)
except StopIteration:
break
In this example, we are manually creating an iterator object using the iter()
function and then using a while loop to iterate over the items in the list. Inside the while loop, we are using the next()
function to get the next item from the iterator object and print it to the console. When there are no more items left in the iterator object, a StopIteration
exception is raised, and the loop ends.
Creating Your Own Iterables
You can also create your own iterables in Python by defining a class that implements the __iter__()
and __next__()
methods. The __iter__()
method should return the object itself, and the __next__()
method should return the next item in the iterable each time it is called.
class MyIterable:
def __init__(self):
self.items = [1, 2, 3, 4, 5]
self.current = 0
def __iter__(self):
return self
def __next__(self):
if self.current < len(self.items):
result = self.items[self.current]
self.current += 1
return result
else:
raise StopIteration
my_iterable = MyIterable()
for item in my_iterable:
print(item)
In this example, we are defining a class called MyIterable
that contains a list of items and implements the __iter__()
and __next__()
methods. The __iter__()
method returns the object itself, and the __next__()
method returns the next item in the list each time it is called. We are then creating an instance of the MyIterable
class and using a for loop to iterate over the items in the iterable and print them to the console.
The Difference Between Iterators and Iterables
- Iterator — The object which is used to iterate over a sequence using the
__next__()
method. - Iterable — Generates an iterator when passed to
iter()
method.
Iterables and iterators are closely related concepts in Python, but they are not the same thing. In simple terms, an iterable is any object that can be looped over using a for loop or other looping constructs, whereas an iterator is an object that generates the next value in a sequence when the next()
method is called on it.
Iterables are objects that implement the __iter__()
method, which returns an iterator object when called. For example, lists, tuples, and sets are all iterable objects in Python, and each of them can be looped over using a for loop.
The iterator object implements the __next__()
method, which returns the next value in the sequence each time it is called.
On the other hand, iterators can implement the __iter__()
method, which returns itself. While the __next__()
method should return the next value in the sequence. When the next()
method is called on an iterator object, it returns the next value in the sequence. Iterators are used to implement custom sequences or streams of data that can be generated on the fly. For example, the range()
function in Python returns an iterator object that generates a sequence of integers.
In summary, an iterable is a collection of values that can be iterated over, while an iterator is an object that generates the values in the sequence one at a time. An iterable can return an iterator when the __iter__()
method is called, and this iterator can be used to generate the values in the sequence. Understanding the difference between these two concepts is essential for effectively working with Python's built-in data structures and creating custom iterable objects.
Iterables That Are Not Iterators
A great example of an iterable that is not an iterator in Python is the string
data type. Although a string can be iterated over using a for loop, it does not implement the __next__()
method that is required for an object to be an iterator. Instead, when you iterate over a string using a for loop, Python automatically creates an iterator object behind the scenes to generate the individual characters in the string:
my_string = 'Hello, World!'
for c in my_string:
print(c)
In this example, my_string
is an iterable that contains a sequence of characters. When we use a for loop to iterate over the string, Python automatically creates an iterator object and calls its __next__()
method to generate each character in the string.
While a string is not an iterator itself, it is still considered an iterable in Python because it can be looped over using a for loop. Other examples of iterables that are not iterators include lists, tuples, sets, and dictionaries, as they all implement the __iter__()
method but not the __next__()
method. To iterate over these objects, Python creates an iterator object behind the scenes to generate the individual items in the collection.
What’s next?
- If you found this story valuable, please consider clapping multiple times (this really helps a lot!)
- Hands-on Practice: Free Python Course
- Full series: 100 Days of Python
- Previous topic: Generators
- Next topic: 10 Most Useful Itertools Methods