About Lesson
Python Iterators
An iterator is an object that allows iteration over a sequence of elements. It implements the iterator protocol, which consists of the __iter__()
and __next__()
methods.
1. Creating an Iterator
To create an iterator in Python, you can use a class that implements the iterator protocol.
Example:
class MyIterator:
def __iter__(self):
self.n = 1
return self
def __next__(self):
if self.n <= 5:
result = self.n
self.n += 1
return result
else:
raise StopIteration
my_iter = MyIterator()
my_iter_iter = iter(my_iter)
print(next(my_iter_iter)) # Output: 1
print(next(my_iter_iter)) # Output: 2
print(next(my_iter_iter)) # Output: 3
print(next(my_iter_iter)) # Output: 4
print(next(my_iter_iter)) # Output: 5
# print(next(my_iter_iter)) # Raises StopIteration
2. Using Iterators with Iterable Objects
Many built-in Python objects are iterable and can be used with iterators.
Example:
my_list = [1, 2, 3, 4, 5]
my_list_iter = iter(my_list)
print(next(my_list_iter)) # Output: 1
print(next(my_list_iter)) # Output: 2
print(next(my_list_iter)) # Output: 3
3. Using Iterators in Loops
Iterators are commonly used in loops to iterate over elements of a sequence.
Example:
my_list = [1, 2, 3, 4, 5]
for item in my_list:
print(item)
Conclusion
Iterators are essential for iterating over sequences of elements in Python. Understanding how to create and use iterators is fundamental for working with iterable objects efficiently.
Join the conversation