Python iter()

Python iter() builtin function is get an iterator for a given object. Optionally we can provide a sentinel, whose use we shall discuss in this tutorial.

In this tutorial, we will learn about the syntax of Python iter() function, and learn how to use this function with the help of examples.

Syntax

The syntax of iter() function is

iter(object[, sentinel])

where

ParameterRequired/OptionalDescription
objectMandatoryAn integer value.
sentinelOptionalA value. If value returned is equal to sentinel, the iterator will stop the iteration.

Returns

The function returns iterator object.

ADVERTISEMENT

Examples

1. iter(object)

When no sentinel is provided, object can be any collection, sequence or object that implement either __iter__() method or __getitem__() method.

In the following program, we will pass a list for object parameter to iter() function.

Python Program

x = [2, 4, 6, 8]
iterator = iter(x)
print(iterator.__next__())
print(iterator.__next__())
Try Online

Output

2
4

We can also use a for loop to print the elements of iterator object.

Python Program

x = [2, 4, 6, 8]
iterator = iter(x)
for item in iterator:
    print(item)
Try Online

Output

2
4
6
8

2. iter() with Custom Class Object

In this example, we will create a class A, which supports iterator protocol. The class accepts x and max, implements an iteration between x and max in steps of 5.

Python Program

class A:
    def __init__(self, x, max):
        self.x = x
        self.max = max

    def __iter__(self):
        return self

    def __next__(self):
        self.x = self.x + 5
        if self.x >= self.max:
            raise StopIteration
        else:
            return self.x

x = A(4, 30)
iterator = iter(x)
for item in iterator:
    print(item)
Try Online

Output

9
14
19
24
29

3. iter() with sentinel Parameter

In this example, we will give sentinel parameter. When we provide an argument for sentinel parameter, the argument that we provide for object parameter must be callable.

Python Program

a = 0

def x():
    global a
    a = a + 2
    return a

iterator = iter(x, 10)
for item in iterator:
    print(item)
Try Online

Output

2
4
6
8

If the object is not callable when sentinel is given, iter() raises TypeError.

Python Program

x = 0

iterator = iter(x, 10)
for item in iterator:
    print(item)
Try Online

Output

Traceback (most recent call last):
  File "d:/workspace/python/example.py", line 3, in <module>
    iterator = iter(x, 10)
TypeError: iter(v, w): v must be callable

Conclusion

In this Python Tutorial, we have learnt the syntax of Python iter() builtin function, and also learned how to use this function, with the help of Python example programs.