The iter() method returns an iterator for the given object.
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.
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: 3output
1
2
3Example 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, 4output
1
2
3
4Example 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, 4output
1
2
3
4