Iterators in Python
Learn how Python iterators allow us to access elements one at a time.
What is an Iterator?
An iterator is an object that allows us to access elements of a collection one at a time.
Python uses the iter() function to create
an iterator and the next() function to
retrieve the next value.
Iterator Flow
Collection
List, tuple, string or another iterable object.
iter()
Creates an iterator object.
next()
Returns the next value from the iterator.
Iterable and Iterator
An iterable is an object whose elements can be accessed one by one.
A list is an iterable. When we use iter()
on the list, Python creates an iterator.
numbers = [10, 20, 30]
iterator = iter(numbers)
Here, numbers is an iterable and
iterator is the iterator object.
Simple Iterator Example
numbers = [10, 20, 30]
iterator = iter(numbers)
print(next(iterator))
print(next(iterator))
print(next(iterator))
Output:
10
20
30
Each call to next() returns the next
element from the iterator.
Using next()
The next() function retrieves the next
available value from an iterator.
colors = ["Red", "Green", "Blue"]
iterator = iter(colors)
print(next(iterator))
print(next(iterator))
Output:
Red
Green
The next value can be retrieved by calling
next() again.
StopIteration
When an iterator has no more values, Python raises
the StopIteration exception.
numbers = [10, 20]
iterator = iter(numbers)
print(next(iterator))
print(next(iterator))
print(next(iterator))
The first two calls return values, but the third call
raises StopIteration.
next() with Default Value
We can provide a default value to next()
so that it does not raise StopIteration
when the iterator is exhausted.
numbers = [10, 20]
iterator = iter(numbers)
print(next(iterator, "No value"))
print(next(iterator, "No value"))
print(next(iterator, "No value"))
Output:
10
20
No value
Iterators with for Loop
The for loop can automatically work with
iterators.
numbers = [10, 20, 30]
for number in numbers:
print(number)
Output:
10
20
30
The for loop internally gets values from
the iterable one by one.
Iterator with String
Strings are also iterable objects.
text = "Python"
iterator = iter(text)
print(next(iterator))
print(next(iterator))
print(next(iterator))
Output:
P
y
t
Iterator with Tuple
courses = ("Python", ".NET", "Java")
iterator = iter(courses)
print(next(iterator))
print(next(iterator))
print(next(iterator))
Output:
Python
.NET
Java
Creating a Custom Iterator
We can create our own iterator by defining
__iter__() and __next__()
methods.
class Numbers:
def __iter__(self):
self.number = 1
return self
def __next__(self):
if self.number <= 3:
value = self.number
self.number += 1
return value
else:
raise StopIteration
numbers = Numbers()
for number in numbers:
print(number)
Output:
1
2
3
Example 🤓👨🏫
The following example uses an iterator to process course names one at a time.
courses = [
"Python",
".NET",
"Java"
]
iterator = iter(courses)
print("Course:", next(iterator))
print("Course:", next(iterator))
print("Course:", next(iterator))
Output:
Course: Python
Course: .NET
Course: Java
Advantages of Iterators
One at a Time
Values can be processed one at a time.
Memory Efficient
Large collections can be processed without creating another complete collection.
Easy to Use
Python loops can work directly with iterables and iterators.
Best Practices
Use for Loop
Prefer a for loop when you simply need to process all values.
Use next Carefully
Remember that next() can raise StopIteration.
Keep Iterators Simple
Custom iterators should have clear and predictable behavior.
Common Mistakes
-
Calling
next()after all values have been consumed. - Forgetting that an iterator keeps its current position.
- Confusing an iterable with an iterator.
- Creating unnecessary custom iterators.
Practice Programs
- Create an iterator from a list of numbers.
-
Use
next()to print each element. - Create an iterator for a string.
- Create an iterator for a tuple.
- Create a custom iterator that generates numbers from 1 to 5.
Summary
An iterator allows Python to access collection elements
one at a time. The iter() function creates
an iterator and the next() function gets
the next value. When no values remain,
StopIteration is raised. Iterators are
useful for processing collections efficiently.