What are Iterators?
Lesson 1 of 13 in Coddy's Python Iterators course.
Iterators are a fundamental concept in Python that allow you to traverse through a collection of elements, one at a time. They provide a way to access the elements of a container object sequentially without needing to know the underlying structure of the container.
What is an Iterator?
An iterator in Python is an object that implements two special methods:
__iter__(): Returns the iterator object itself.__next__(): Returns the next value in the iteration.
Iterators are used to iterate over iterable objects. When you use a for loop in Python, you're using an iterator behind the scenes.
Iterable vs Iterator
It's important to understand the difference between an iterable and an iterator:
| Iterable | Iterator |
|---|---|
| An object capable of returning its elements one at a time | An object representing a stream of data |
Implements __iter__() method |
Implements both __iter__() and __next__() methods |
| Examples: lists, tuples, strings | Created from an iterable using iter() function |
Example of Using an Iterator
Here's a simple example of how to use an iterator in Python:
my_list = [1, 2, 3, 4, 5]
my_iterator = iter(my_list)
print(next(my_iterator)) # Output: 1
print(next(my_iterator)) # Output: 2
print(next(my_iterator)) # Output: 3
In this example, my_list is an iterable, and my_iterator is the iterator created from it using the iter() function. We then use the next() function to retrieve elements from the iterator one by one.
Iterators play a crucial role in Python by providing a memory-efficient way to handle large datasets and allowing for lazy evaluation of data.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
Try it yourself
This lesson doesn't include a code challenge.