An iterator in Python is an object that holds a sequence of values and provide sequential traversal through a collection of items such as lists, tuples and dictionaries. . The Python iterators object is initialized using the iter() method. It uses the next() method for iteration.
- __iter__(): __iter__() method initializes and returns the iterator object itself.
- __next__(): the __next__() method retrieves the next available item, throwing a StopIteration exception when no more items are available.
Difference between Iterator and Iterable
Iterables are objects that can return an iterator. These include built-in data structures like lists, dictionaries, and sets. Essentially, an iterable is anything you can loop over using a for loop. An iterable implements the __iter__() method, which is expected to return an iterator object.
Iterators are the objects that actually perform the iteration. They implement two methods: __iter__() and __next__(). The __iter__() method returns the iterator object itself, making iterators iterable as well.
Python iter() Example
Python
s = "GFG"
it = iter(s)
print(next(it))
print(next(it))
print(next(it))
Creating an iterator
Creating a custom iterator in Python involves defining a class that implements the __iter__() and __next__() methods according to the Python iterator protocol.
- Define the Class: Start by defining a class that will act as the iterator.
- Initialize Attributes: In the __init__() method of the class, initialize any required attributes that will be used throughout the iteration process.
- Implement __iter__(): This method should return the iterator object itself. This is usually as simple as returning self.
- Implement __next__(): This method should provide the next item in the sequence each time it's called.
Below is an example of a custom class called EvenNumbers, which iterates through even numbers starting from 2:
Python
class EvenNumbers:
def __iter__(self):
self.n = 2 # Start from the first even number
return self
def __next__(self):
x = self.n
self.n += 2 # Increment by 2 to get the next even number
return x
# Create an instance of EvenNumbers
even = EvenNumbers()
it = iter(even)
# Print the first five even numbers
print(next(it))
print(next(it))
print(next(it))
print(next(it))
print(next(it))
Explanation:
- Initialization: The __iter__() method initializes the iterator at 2, the first even number.
- Iteration: The __next__() method retrieves the current number and then increases it by 2, ensuring the next call returns the subsequent even number.
- Usage: We create an instance of EvenNumbers, turn it into an iterator and then use the next() function to fetch even numbers one at a time.
StopIteration Exception
The StopIteration exception is integrated with Python’s iterator protocol. It signals that the iterator has no more items to return. Once this exception is raised, further calls to next() on the same iterator will continue raising StopIteration.
Example:
Python
li = [100, 200, 300]
it = iter(li)
# Iterate until StopIteration is raised
while True:
try:
print(next(it))
except StopIteration:
print("End of iteration")
break
Output100
200
300
End of iteration
In this example, the StopIteration exception is manually handled in the while loop, allowing for custom handling when the iterator is exhausted.
Similar Reads
Difference between == and is operator in Python In Python, == and is operators are both used for comparison but they serve different purposes. The == operator checks for equality of values which means it evaluates whether the values of two objects are the same. On the other hand, is operator checks for identity, meaning it determines whether two
4 min read
Python | Set 3 (Strings, Lists, Tuples, Iterations) In the previous article, we read about the basics of Python. Now, we continue with some more python concepts. Strings in Python: A string is a sequence of characters that can be a combination of letters, numbers, and special characters. It can be declared in python by using single quotes, double quo
3 min read
Python String A string is a sequence of characters. Python treats anything inside quotes as a string. This includes letters, numbers, and symbols. Python has no character data type so single character is a string of length 1.Pythons = "GfG" print(s[1]) # access 2nd char s1 = s + s[0] # update print(s1) # printOut
6 min read
Python Lists In Python, a list is a built-in dynamic sized array (automatically grows and shrinks). We can store all types of items (including another list) in a list. A list may contain mixed type of items, this is possible because a list mainly stores references at contiguous locations and actual items maybe s
6 min read
Python Tuples A tuple in Python is an immutable ordered collection of elements. Tuples are similar to lists, but unlike lists, they cannot be changed after their creation (i.e., they are immutable). Tuples can hold elements of different data types. The main characteristics of tuples are being ordered , heterogene
6 min read
Python Sets Python set is an unordered collection of multiple items having different datatypes. In Python, sets are mutable, unindexed and do not contain duplicates. The order of elements in a set is not preserved and can change.Creating a Set in PythonIn Python, the most basic and efficient method for creating
10 min read
Dictionaries in Python A Python dictionary is a data structure that stores the value in key: value pairs. Values in a dictionary can be of any data type and can be duplicated, whereas keys can't be repeated and must be immutable. Example: Here, The data is stored in key:value pairs in dictionaries, which makes it easier t
5 min read
Python Arrays Lists in Python are the most flexible and commonly used data structure for sequential storage. They are similar to arrays in other languages but with several key differences:Dynamic Typing: Python lists can hold elements of different types in the same list. We can have an integer, a string and even
9 min read
Python If Else Statements - Conditional Statements In Python, If-Else is a fundamental conditional statement used for decision-making in programming. If...Else statement allows to execution of specific blocks of code depending on the condition is True or False.if Statementif statement is the most simple decision-making statement. If the condition ev
4 min read
Loops in Python - For, While and Nested Loops Loops in Python are used to repeat actions efficiently. The main types are For loops (counting through items) and While loops (based on conditions). Additionally, Nested Loops allow looping within loops for more complex tasks. While all the ways provide similar basic functionality, they differ in th
9 min read