The iter()
function converts an iterable (like a list, tuple, or string) into an iterator, allowing elements to be accessed one at a time. It’s useful for looping through data, working with custom objects, and controlling iteration manually.
Example
numbers = [1, 2, 3]
iterator = iter(numbers)
print(next(iterator)) # Output: 1
print(next(iterator)) # Output: 2
print(next(iterator)) # Output: 3
The next()
function fetches the next item from the iterator.
Syntax
iter(iterable)
- iterable → A list, tuple, string, or any object that supports iteration.
- Returns → An iterator object.
1. Iterating Over Strings with iter()
word = "Python"
iterator = iter(word)
print(next(iterator)) # Output: P
print(next(iterator)) # Output: y
Great for processing characters one by one.
2. Using iter()
in a Loop
Instead of next()
, use for
loops to automatically iterate.
numbers = [10, 20, 30]
iterator = iter(numbers)
for num in iterator:
print(num)
Loops automatically call next()
until all items are exhausted.
3. Creating an Iterator from a Custom Object
Define an iterable class using iter()
and next()
.
class Counter:
def __init__(self, start, end):
self.current = start
self.end = end
def __iter__(self):
return self
def __next__(self):
if self.current > self.end:
raise StopIteration
self.current += 1
return self.current - 1
counter = Counter(1, 3)
for num in counter:
print(num)
Output:
1
2
3
Useful for custom iteration logic.
4. Using iter()
with a Sentinel Value
Convert a function into an iterator until a stop value is reached.
import random
rand_iterator = iter(lambda: random.randint(1, 10), 5)
for num in rand_iterator:
print(num) # Stops when 5 is generated
This is great for reading files or streams.
Key Notes
- ✔ Creates an iterator from any iterable.
- ✔ Use
next()
to access items manually. - ✔ Loops automatically call
next()
for you. - ✔ Can define custom objects as iterators.
By using iter()
, you can process data efficiently, control iteration, and create reusable iterators. 🚀