The iter()
function in Python is a built-in function that returns an iterator object from an iterable. An iterator is an object that can be iterated (looped) over, and it provides a way to access the elements of the iterable one by one, without loading the entire iterable into memory.
The iter()
function takes one or two arguments:
Here are a few examples to illustrate the usage of the iter()
function:
Creating an iterator from a list
my_list = [1, 2, 3, 4, 5]
my_iterator = iter(my_list)
print(next(my_iterator)) # Output: 1
print(next(my_iterator)) # Output: 2
print(next(my_iterator)) # Output: 3
Creating an iterator using a callable object and sentinel value
import random
def generate_random_number():
return random.randint(1, 10)
# Create an iterator that generates random numbers until 7 is generated
my_iterator = iter(generate_random_number, 7)
print(next(my_iterator)) # Output: (random number between 1 and 6)
print(next(my_iterator)) # Output: (random number between 1 and 6)
print(next(my_iterator)) # Output: (random number between 1 and 6)
In both examples, the next()
function is used to retrieve the next element from the iterator. When there are no more elements to retrieve, a StopIteration
exception is raised.