Python iter() Function
The iter()
method returns an iterator for the given object.
An iterator object allows you to iterate over a collection of data, such as lists, tuples, dictionaries, and sets, in a memory-efficient manner.
Syntax
iter(object, sentinel)
iter() Parameters
Python iter()
function parameters:
Parameter | Condition | Description |
---|---|---|
object | Required | An iterable object like list, set, tuple, etc. |
sentinel | Option | Special value that is used to represent the end of a sequence |
iter() Return Value
Python iter()
function returns an iterator object for the given argument until the sentinel character is found.
It raises TypeError
for a user-defined object that doesn't implement __iter__()
, and __next__()
or __getitem()__
.
Examples
Example 1: Iterating over a List
Let's iterate over a list:
my_list = [1, 2, 3, 4, 5]
my_iter = iter(my_list)
print(next(my_iter)) # Output: 1
print(next(my_iter)) # Output: 2
print(next(my_iter)) # Output: 3
output
1
2
3
Example 2: Iterating Using a Sentinel Value
Let's use a sentinel value to stop the iteration. Just specify the value as second parameter of the iter()
function
def counter():
count = 0
def increase():
nonlocal count
count += 1
return count
return increase
cnt = counter()
iterator = iter(cnt, 5)
for count in iterator:
print(count) # Output: 1, 2, 3, 4
output
1
2
3
4
The value of the sentinel parameter here is 5
so the program will stop when the value from the __next__()
method is equal to this number!
Example 3: Implement an Iterable User-Defined Class
class CounterIterator:
def __init__(self, fn, sentinel):
self.fn = fn
self.sentinel = sentinel
def __iter__(self):
return self
def __next__(self):
current = self.fn()
if current == self.sentinel:
raise StopIteration
return current
cnt = counter()
iterator = CounterIterator(cnt, 5)
for count in iterator:
print(count) # Output: 1, 2, 3, 4
output
1
2
3
4