iter() Function in Python

Python iter() Function

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:

  • If a single argument is provided, it should be an object that supports iteration, such as a list, string, tuple, or dictionary. The function returns an iterator object that can be used to iterate over the elements of the iterable.
  • If two arguments are provided, the first argument should be a callable object (usually a function) and the second argument should be a sentinel value. In this case, the function returns an iterator that repeatedly calls the callable object until it returns the sentinel value.

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.