next() is a built-in Python function used to:
✔ Retrieve the next item from an iterator
✔ Manually control iteration
✔ Work directly with generators & iterables
Basic idea:
next(iterator)
Python iteration works like this:
Iterable → Iterator → next() → Value
Key insight:
for loop internally uses next()
numbers = [1, 2, 3]
iterator = iter(numbers)
print(next(iterator))
print(next(iterator))
print(next(iterator))
Output:
1
2
3
✔ Each call moves forward.
next(iterator) → iterator.__next__()
Yes.
next() simply calls:
__next__()
Behind the scenes.
print(next(iterator)) # After last value
ERROR:
StopIteration
✔ Means no more values.
next(iterator, default_value)
Example:
numbers = [1, 2]
iterator = iter(numbers)
print(next(iterator))
print(next(iterator))
print(next(iterator, "No more items"))
Output:
1
2
No more items
✔ Prevents crash.
text = "ABC"
iterator = iter(text)
print(next(iterator))
print(next(iterator))
print(next(iterator))
Output:
A
B
C
✔ Strings are iterable.
def generator():
yield 10
yield 20
gen = generator()
print(next(gen))
print(next(gen))
Output:
10
20
✔ next() resumes generator execution.
for num in [1, 2, 3]:
print(num)
iterator = iter([1, 2, 3])
print(next(iterator))
print(next(iterator))
✔ Useful for fine-grained control.
You can define your own iteration logic.
Example:
class Counter:
def __init__(self, max):
self.max = max
self.current = 0
def __iter__(self):
return self
def __next__(self):
if self.current >= self.max:
raise StopIteration
self.current += 1
return self.current
counter = Counter(3)
print(next(counter))
print(next(counter))
print(next(counter))
Output:
1
2
3
✔ Manual iteration design.
Any iterator must implement:
✔ iter()
✔ next()
Python relies on this contract.
next([1, 2, 3]) # ERROR
✔ Because list is not an iterator.
Correct usage:
next(iter([1, 2, 3]))
Always handle exhaustion safely.
Once consumed → Gone.
iterable = [1, 2, 3]
it1 = iter(iterable)
it2 = iter(iterable)
✔ Separate state.
Iterator ≠ Random access.
next() enables:
✔ Manual iteration control
✔ Lazy evaluation mechanics
✔ Generator execution stepping
✔ Custom iteration design
✔ Streaming logic
Core of Python’s iteration engine.
✔ Manual iteration control
✔ Working with generators
✔ Custom iterators
✔ Streaming pipelines
✔ Look-ahead logic
Rare in simple loops.
✔ Use default value when unsure
✔ Handle StopIteration safely
✔ Prefer loops unless control needed
✔ Avoid unnecessary manual iteration
✔ next() retrieves next value
✔ Works on iterators only
✔ Calls next() internally
✔ StopIteration signals end
✔ Supports default fallback
✔ Critical for generators
✔ Core of iteration protocol
- Use next() with list iterator
- Trigger StopIteration
- Use default fallback
- Use next() with string
- Use next() with generator
- Build custom iterator
- Implement iterator protocol
- Compare loop vs next()