Bird
Raised Fist0
PythonConceptBeginner · 3 min read

What is Iterator in Python: Simple Explanation and Example

An iterator in Python is an object that lets you go through all the items in a collection one by one, like reading pages in a book. It uses the __iter__() and __next__() methods to keep track of where you are and to get the next item until there are no more.
⚙️

How It Works

Think of an iterator like a bookmark in a book. When you read a book, you don't read all pages at once; you read one page at a time and use a bookmark to remember where you stopped. Similarly, an iterator remembers the current position in a collection (like a list or a set) and gives you the next item when you ask for it.

In Python, an iterator is any object that has two special methods: __iter__(), which returns the iterator object itself, and __next__(), which returns the next item. When there are no more items, __next__() raises a StopIteration exception to signal the end.

This mechanism allows Python to loop over collections efficiently without loading everything at once, which is helpful for large data or streams.

💻

Example

This example shows how to create an iterator from a list and use it to get items one by one.

python
numbers = [10, 20, 30]
iterator = iter(numbers)  # Get iterator from the list

print(next(iterator))  # Output: 10
print(next(iterator))  # Output: 20
print(next(iterator))  # Output: 30

# next(iterator) now would raise StopIteration
Output
10 20 30
🎯

When to Use

Use iterators when you want to process items one at a time without loading everything into memory. This is useful for reading large files, streaming data, or looping over custom collections.

For example, when reading a big text file, an iterator can read one line at a time instead of loading the whole file. Also, iterators let you create your own objects that can be looped over with for loops, making your code cleaner and more flexible.

✅

Key Points

  • An iterator remembers its current position in a collection.
  • It uses __iter__() and __next__() methods.
  • When no items are left, StopIteration is raised.
  • Iterators help handle large data efficiently.
  • You can create custom iterators for your own objects.
✅

Key Takeaways

An iterator lets you access items one by one from a collection.
It uses special methods __iter__() and __next__() to work.
When items run out, it raises StopIteration to stop.
Iterators are useful for handling large or streaming data efficiently.
You can make your own iterators to customize looping behavior.