iter

Full name
iter
Library
Built-in
Syntax

iter(object [, sentinel])

Description

The iter function returns an iterable object from another object. In its simplest configuration it will only receive one argument -the object to be made iterable-. This requires that said object support the iteration or sequence protocols (__iter__ and __getitem__ methods respectively). If none of them are supported, the iter function will return a type error (TypeError).

If the iter function receives a second argument ("sentinel"), the object included as first argument must be of type callable (including the __call__ method). In this case, the iterator generated by iter will invoke the object for each execution of the __next __() method: If the value received is equal to sentinel, an exception of type StopIteration will be generated. Otherwise the received value will be returned (see example below).

Parameters
  • object: Object to convert to iterable.
  • sentinel: Value for which the generated iterable will return an exception of type StopIteration.
Result

The iter function returns an iterable.

Examples

If we start from the following list:

a = [2, 4, 6, 8]

...we can make it an iterable with the following code:

a_iter = iter(a)
a_iter

It is possible to use the next function to extract the values from the iterable:

next(a_iter)

2

next(a_iter)

4

To test the use of the second argument, sentinel, let's create a function ("callable" object) that, for example, generates a random integer between 0 and 5, both included:

import random

def f():
    return random.randint(0, 5)

Now let's make it iterable by indicating the number 3 as sentinel:

f_iter = iter(f, 3)

This means that every time the next function is executed on f_iter, the value obtained will be compared with the number 3 and, if it matches, an exception will be generated:

while True:
    print(next(f_iter))

4
0
1
5
2
-------------------------------------------------- -------------------------
StopIteration Traceback (most recent call last)
in
1 while True:
----> 2 print (next (f_iter))

StopIteration:

Submitted by admin on Thu, 01/14/2021 - 17:41