Skip to content

Python iter() Function

How the Python iter() function creates an iterator for lists, tuples, dictionaries, and custom objects, with optional sentinel values to control iteration.

The iter() method returns an iterator for the given object.

Syntax

iter(object, sentinel)

iter() Parameters

Python iter() function parameters:

Parameter Condition Description
object Required An iterable object like list, set, tuple, etc.
sentinel Option Special value that is used to represent the end of a sequence

iter() Return Value

Python iter() function returns an iterator object for the given argument until the sentinel character is found.

Examples

Example 1: Iterating over a List

Let's iterate over a list:

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

print(next(my_iter))  # Output:  1
print(next(my_iter))  # Output:  2
print(next(my_iter))  # Output:  3

output

1
2
3

Example 2: Iterating Using a Sentinel Value

Let's use a sentinel value to stop the iteration. Just specify the value as second parameter of the iter() function

def counter():
    count =  0
    def increase():
        nonlocal count
        count +=  1
        return count
    return increase

cnt = counter()
iterator = iter(cnt,  5)

for count in iterator:
    print(count)  # Output:  1,  2,  3,  4

output

1
2
3
4

Example 3: Implement an Iterable User-Defined Class

class CounterIterator:
    def __init__(self, fn, sentinel):
        self.fn = fn
        self.sentinel = sentinel

    def __iter__(self):
        return self

    def __next__(self):
        current = self.fn()
        if current == self.sentinel:
            raise StopIteration
        return current

cnt = counter()
iterator = CounterIterator(cnt,  5)

for count in iterator:
    print(count)  # Output:  1,  2,  3,  4

output

1
2
3
4
Navigation