Distinguish an iterable from the iterator that consumes its items.
What You Will Learn
An iterable supplies an iterator through iter(); an iterator supplies successive values through next() and signals exhaustion with StopIteration. A list can be traversed repeatedly, while a generator or list iterator is normally single-use.
A generator is also an iterator; a list is iterable but not an iterator.
Many iterator tools are lazy. Creating the iterator does not necessarily perform the work; advancing it can consume the original source.
Step-by-Step Example
The example below makes the behavior visible with small input values that you can change safely.
items = ["red", "green", "blue"]
item_iterator = iter(items)
print(next(item_iterator))
print(list(item_iterator))
print(list(items))
How the Example Works
- The variable items holds the result of ['red', 'green', 'blue']. Later lines use that value or inspect how it changes.
- The variable item_iterator holds the result of iter(items). Later lines use that value or inspect how it changes.
- The print() calls make the return values or state visible so you can compare them with the explanation and check your prediction.
Expected output from the example:
red
['green', 'blue']
['red', 'green', 'blue']
When You Would Use This
This pattern is useful in readers for CSV files, event streams, or paginated API results, where collecting everything in memory is unnecessary. Because iterator state advances when values are consumed, decide whether you need a reusable collection or a one-time pass. Keep files and connections open until their lazy consumers finish.
Practice: Modify the Code
Create an iterator and read its first item before collecting the rest.
Verify the changed output against the behavior described above, including the relevant invalid or boundary case.
For complete parameters and version details, consult the official Python documentation.
Common Beginner Mistakes
- Assuming every iterable supports next() directly without first calling iter().
- Trying to reuse an exhausted iterator as though it restarts automatically.
Key Takeaways
- Distinguish an iterable from the iterator that consumes its items.
- An iterable supplies an iterator through iter(); an iterator supplies successive values through next() and signals exhaustion with StopIteration.
- A generator is also an iterator; a list is iterable but not an iterator.