Python Tutorial
Python Variable
Python Operators
Python Sequence
Python String
Python Flow Control
Python Functions
Python Class and Object
Python Class Members (properties and methods)
Python Exception Handling
Python Modules
Python File Operations (I/O)
An iterator in Python is an object that implements the iterator protocol, which consists of the methods __iter__()
and __next__()
. Iterators are used to iterate over a collection of items, such as elements in a list, keys in a dictionary, or lines in a file. In this tutorial, we'll show you how to create and use custom iterators in Python.
__iter__()
and __next__()
methods. The __iter__()
method should return the iterator object itself (usually self
), and the __next__()
method should return the next value in the sequence. If there are no more items to return, the __next__()
method should raise the StopIteration
exception.Example:
class CountUpTo: def __init__(self, limit): self.limit = limit self.current = 0 def __iter__(self): return self def __next__(self): if self.current > self.limit: raise StopIteration else: self.current += 1 return self.current - 1
counter = CountUpTo(5)
for
loop:
You can use a for
loop to automatically iterate over the iterator. The loop will continue until the StopIteration
exception is raised.for number in counter: print(number)
Output:
0 1 2 3 4 5
next()
function:
You can also use the next()
function to manually iterate over the iterator, one item at a time.counter = CountUpTo(3) print(next(counter)) # Output: 0 print(next(counter)) # Output: 1 print(next(counter)) # Output: 2 print(next(counter)) # Output: 3
StopIteration
exception:
When the iterator is exhausted, the next()
function will raise a StopIteration
exception. You can catch this exception to handle the end of the iteration gracefully.counter = CountUpTo(1) print(next(counter)) # Output: 0 print(next(counter)) # Output: 1 try: print(next(counter)) except StopIteration: print("Iteration is finished.")
Output:
0 1 Iteration is finished.
In this tutorial, you learned how to create and use custom iterators in Python by implementing the __iter__()
and __next__()
methods in a class. Iterators provide a memory-efficient and flexible way to work with sequences of items and can be used with built-in Python functions and control structures like for
loops and comprehensions.
How to create an iterator in Python:
class MyIterator: def __init__(self, data): self.data = data self.index = 0 def __iter__(self): return self def __next__(self): if self.index < len(self.data): result = self.data[self.index] self.index += 1 return result else: raise StopIteration my_list = [1, 2, 3, 4, 5] my_iterator = MyIterator(my_list) for item in my_iterator: print(item)
Iterating over objects in Python using iterators:
my_list = [1, 2, 3, 4, 5] my_iterator = iter(my_list) for item in my_iterator: print(item)
Iterating through lists with Python iterators:
my_list = [1, 2, 3, 4, 5] my_iterator = iter(my_list) for item in my_iterator: print(item)
Creating custom iterators in Python:
class MyIterator: def __init__(self, data): self.data = data self.index = 0 def __iter__(self): return self def __next__(self): if self.index < len(self.data): result = self.data[self.index] self.index += 1 return result else: raise StopIteration my_list = [1, 2, 3, 4, 5] my_iterator = MyIterator(my_list) for item in my_iterator: print(item)
Working with for loops and iterators in Python:
my_list = [1, 2, 3, 4, 5] for item in my_list: print(item)
Using the iter()
function in Python:
my_list = [1, 2, 3, 4, 5] my_iterator = iter(my_list) for item in my_iterator: print(item)
Advanced iterator usage in Python:
class Fibonacci: def __init__(self): self.prev = 0 self.current = 1 def __iter__(self): return self def __next__(self): result = self.prev self.prev, self.current = self.current, self.prev + self.current return result fib_sequence = Fibonacci() for _ in range(10): print(next(fib_sequence))