The iter()
function in Python is a built-in function that returns an iterator object from an iterable. It can be called with one or two arguments, where the first argument is the iterable object and the second argument is a sentinel value that determines when to stop iteration. If the second argument is not provided, the iter()
function simply returns an iterator for the given iterable.
Parameter Values
Parameter | Description |
---|---|
object | A collection that you want to iterate over using the iterator object. |
sentinel | A value that defines the end of the iteration, once this value is reached, the iterator will stop. |
Return Values
The iter()
function returns an iterator object or a callable with a __next__
method.
How to Use iter()
in Python
The iter()
function returns an iterator object for the given iterable that can be used to iterate over the elements of the iterable.
numbers = [1, 2, 3, 4, 5]
iter_numbers = iter(numbers)
print(next(iter_numbers))
print(next(iter_numbers))
The iter()
function can also be used with a custom iterable class by implementing the __iter__() and __next__() methods.
class MyRange:
def __iter__(self):
self.num = 1
return self
def __next__(self):
if self.num <= 5:
result = self.num
self.num += 1
return result
else:
raise StopIteration
numbers = MyRange()
iter_numbers = iter(numbers)
print(next(iter_numbers))
print(next(iter_numbers))
The iter()
function can take an additional argument which is a callable that will be called until it returns the specified value.
import random
def random_num():
return random.randint(1, 10)
iter_random = iter(random_num, 5)
for num in iter_random:
print(num)