Iterators
Iterators
You have used loops many times.
Example:
for item in [1, 2, 3]:
print(item)
But have you ever wondered how Python gets one item at a time?
It uses iterators.
What Is an Iterator?
An iterator is an object that gives values one at a time.
Instead of returning everything at once, it returns the next item when asked.
Why Iterators Matter
Iterators help Python:
- run
forloops - process data step by step
- save memory
- work with large data
Iterable vs Iterator
Iterable
An iterable is something you can loop through.
Examples:
- list
- tuple
- string
- dictionary
- set
Iterator
An iterator is what Python uses behind the scenes to get values one by one.
Create an Iterator
Use iter().
numbers = [10, 20, 30]
it = iter(numbers)
print(it)
Example Output
<list_iterator object at ...>
Get Values with next()
Use next() to get the next item.
numbers = [10, 20, 30]
it = iter(numbers)
print(next(it))
print(next(it))
print(next(it))
Output
10
20
30
What Happens After the Last Item?
print(next(it))
Python raises:
StopIteration
This means there are no more values.
How for Loop Uses Iterators
This loop:
for number in [1, 2, 3]:
print(number)
Works like this idea:
it = iter([1, 2, 3])
print(next(it))
print(next(it))
print(next(it))
Iterator with String
text = "ABC"
it = iter(text)
print(next(it))
print(next(it))
print(next(it))
Output
A
B
C
Safe next()
Use a default value.
numbers = [1]
it = iter(numbers)
print(next(it, "Done"))
print(next(it, "Done"))
Output
1
Done
Code Along
Create an iterator from:
["Pen", "Book", "Bag"]
Use next() three times.
Mini Challenge
Create an iterator from:
(5, 10, 15)
Tasks:
- Print first value
- Print second value
- Print third value
Expected output:
5
10
15
Real World Use Case
Iterators are used in loops, files, generators, data streams, and large datasets.
Quiz
- What is an iterator?
- What is the difference between iterable and iterator?
- What does
next()do? - What error happens when values are finished?
Assignment
Create an iterator from a string and print each character using next().
Summary
You learned how iterators return values one at a time and power Python loops.