Introduction to Iterators in Python
Have you ever wondered how Python handles looping through collections such as lists or dictionaries? This is where iterators come into play. An iterator in Python is an object that contains a countable number of values and can be iterated upon, meaning you can traverse through all the values. Let's understand more!
Iterators in Python are implemented using the __iter__() and __next__() methods.
- __iter__(): This method is used to initialize an iterator that returns an iterator object.
- __next__(): This method is used to return the next value within an iterable. This method raises a StopIteration signal at the completion of iterations over the iterable.
Iterators in Python come in pretty handy while dealing with a huge amount of data. Here rather than storing all the data in the memory, we work with small chunks of data, and once done processing, we further can use an iterator to stream the rest of the data and start processing the same. This reduces the burden on our computer’s memory.
Now that we have a basic understanding of iterators in Python let’s take a look at the following key concepts associated with them.
- Difference between Iterable and Iterator
- Using for loop as Iterator in Python
- Creating Custom Iterators in Python
Difference Between Iterable and Iterator
In Python, objects like lists, tuples, strings, sets, etc, are known as iterable objects as they act as a container that can be iterated over using iterators. The iter() is used upon the iterable objects to generate iterators. Take a look at the below example for reference.
Example:
# initialize an iterable # object(ie, list) my_list = [1,2,3,4,5] #initialize an iterator object # using iter() method my_iterator = iter(my_list) # iterate my_list once by # calling next() method print(next(my_iterator)) # iterate my_list twice by # calling next() method print(next(my_iterator)) # iterate my_list thrice by # calling next() method
print(next(my_iterator))
Output
1
2
3
Best-suited Python courses for you
Learn Python with these high-rated online courses
Using the for Loop as Iterator
We can also make use of the for loop to iterate over an iterable object. Take a look at the below example for reference.
Example: Using for loop to iterate over an iterable object.
# initialize a string, that # is an iterable object in python my_string = "Shiksha" # iterate over my_string using for loop for i in my_string: print(i)
Output:
S
h
i
k
s
h
a
Creating Iterators in Python
We make use of the __iter__() and the __next__() method to implement Python iterators. Take a look at the below example for reference.
Example: A simple Python program to demonstrate the working of iterators using an example type that iterates from 0 to a given value.
class MyIterable: # Constructor def __init__(self, max_value): self.max_value = max_value
# Initialize iterator and # create the iterator object def __iter__(self): self.a = 0 return self
# Method to get to the next element # of the iterable def __next__(self): # Store current value of a a = self.a
# Stop iteration if # max_value is reached if a > self.max_value: raise StopIteration
# Else increment and return old value self.a += 1 return a
# Prints numbers from 0 to 5 for i in MyIterable(5): print(i)
Output:
0
1
2
3
4
5
Conclusion:
In this article, we have managed to cover the following concepts associated with Python iterators:
- What are Python iterators?
- Why use Python iterators?
- Difference between iterable and iterators.
- Built-in Python iterators
- Creating a custom Python iterator
This is a collection of insightful articles from domain experts in the fields of Cloud Computing, DevOps, AWS, Data Science, Machine Learning, AI, and Natural Language Processing. The range of topics caters to upski... Read Full Bio