SoFunction
Updated on 2025-04-14

Specific use of iter function in Python

Because I came into contact with this function in jax code, I was not very familiar with it. Every time I saw the name, I only knew it was iterating, but I didn’t know how it iterated, so I wrote the following notes to remind myself.

def iter(source, sentinel=None): # known special case of iter
    """
    iter(iterable) -> iterator
    iter(callable, sentinel) -> iterator
    
    Get an iterator from an object.  In the first form, the argument must
    supply its own iterator, or be a sequence.
    In the second form, the callable is called until it returns the sentinel.
    """
    pass

Iter function in Python

In Python programming,iterFunctions are a very useful built-in function for creating iterator objects. An iterator is an object that allows you to iterate over elements in a collection (such as lists, tuples, dictionaries, etc.).iterThere are two main uses of functions:

iter(iterable) -> iterator

This form accepts an iterable object (such as lists, tuples, dictionaries, etc.) and returns an iterator. Iterators can be used to iterate over elements of an iterable object.

For example:

my_list = [1, 2, 3, 4, 5]
iterator = iter(my_list)

print(next(iterator))  # Output: 1print(next(iterator))  # Output: 2

iter(callable, sentinel) -> iterator

This form accepts a callable object (such as a function) and a sentinel value. It calls the callable object until the sentinel value is returned.

For example:

import random

def my_callable():
    return (1, 10)

iterator = iter(my_callable, 5)

print(next(iterator))  # Output: Random integers between 1 and 10print(next(iterator))  # Output: Random integers between 1 and 10

Assuming that the sequence of random numbers returned by the my_callable function is [3, 7, 5, 2, 8], the output of the code may be:

print(next(iterator))  # Output: 3print(next(iterator))  # Output: 7

When the my_callable function returns 5, the iterator stops because 5 is the sentinel value.

Custom iter function

To better understanditerHow the function works, we can implement a simple custom version:

def iter(source, sentinel=None):
    if sentinel is None:
        # Form 1: iter(iterable)
        return source.__iter__()
    else:
        # Form 2: iter(callable, sentinel)
        while True:
            value = source()
            if value == sentinel:
                break
            yield value

This is the introduction to this article about the specific use of iter functions in Python. For more related content of Python iter functions, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!