Iterators in Python provide a way to traverse through a sequence (such as lists, tuples, or strings) one element at a time. They are a fundamental part of Python’s iteration protocol.
What is an Iterator?
An iterator is an object in Python that implements the __iter__() and __next__() methods.
__iter__()returns the iterator object itself.__next__()returns the next element in the sequence and raisesStopIterationwhen there are no more elements.
Creating an Iterator
You can create an iterator by defining a class with __iter__() and __next__() methods.
class Counter:
def __init__(self, start, end):
self.current = start
self.end = end
def __iter__(self):
return self
def __next__(self):
if self.current > self.end:
raise StopIteration
value = self.current
self.current += 1
return value
counter = Counter(1, 5)
for num in counter:
print(num)
Output:
1
2
3
4
5
Using Built-in Iterators
Python provides built-in iterators for iterable objects like lists, tuples, and strings.
my_list = [10, 20, 30]
iterator = iter(my_list)
print(next(iterator)) # 10
print(next(iterator)) # 20
print(next(iterator)) # 30
Iterators vs. Iterables
- An iterable is an object that can return an iterator (e.g., lists, tuples, sets).
- An iterator is an object that keeps state and produces the next value when
next()is called.
You can check if an object is an iterator using iter(), and get the next value using next().
Generator Functions (Simpler Iterators)
Generators simplify iterator creation using yield instead of return.
def count_up(start, end):
while start <= end:
yield start
start += 1
for num in count_up(1, 5):
print(num)
Key Takeaways
- Iterators allow sequential data traversal in your Python projects using
__iter__()and__next__(). - Python’s built-in objects like lists and tuples support iteration.
- Generators provide a simpler way to create iterators using
yield.
Practice Exercise
Here's a simple challenge, open up your Python editor and try to create a custom iterator that iterates through even numbers:
class EvenNumbers:
def __init__(self, start, end):
self.current = start if start % 2 == 0 else start + 1
self.end = end
def __iter__(self):
return self
def __next__(self):
if self.current > self.end:
raise StopIteration
value = self.current
self.current += 2
return value
for num in EvenNumbers(2, 10):
print(num)
Wrapping Up
Understanding iterators is key to writing efficient loops and handling large datasets. Whether using built-in iterators or creating custom ones, mastering iteration helps streamline data processing. Happy coding!