iter()
The iter()
function is a built-in function in Python that returns an iterator from an iterable object, such as a list, tuple, string, or any object that implements the iterator protocol.
Syntax
iter(object, sentinel)
object
: A required argument that represents an iterable object such as a list, tuple, string, or any object that follows iterator or sequence protocol.sentinel
: An optional argument that represents the end of the sequence.
Note:
sentinel
parameter is used to repeatedly call a function until a specific value is returned, which stops the iteration.
Example 1
This example demonstrates the use of the iter()
function to create an iterator from a list and retrieve its elements one by one using the next()
function:
# Example of iter() function without sentinelfruits = ['apples', 'bananas', 'oranges']# Creating an iterator from the listmy_iterator = iter(fruits)print('Fruits:')print(next(my_iterator))print(next(my_iterator))print(next(my_iterator))
The output would be:
Fruits:applesbananasoranges
Example 2
This example demonstrates the use of the iter()
function with a callable and a sentinel
value, repeatedly calling the function until the sentinel
is returned:
from functools import partialimport random# iter() method with a callable and a sentinel argument os 7def get_random_num(a, b):return random.randint(a, b)another_iterator = iter(partial(get_random_num, 1, 10), 7)print('\nNumbers: ')# Loop will run till 7 is returnedfor i in another_iterator:print(i)
The output would be:
Numbers:2816958295294
Note: The output varies with each execution due to random integer generation, continuing until the sentinel value is encountered.
Codebyte Example
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.