iter(object [, sentinel])
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).
- object: Object to convert to iterable.
- sentinel: Value for which the generated iterable will return an exception of type StopIteration.
The iter function returns an iterable.
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)
1 while True:
----> 2 print (next (f_iter))
StopIteration: