ScanSkill

iter

This iter() function returns an iterator object.

Syntax

iter(object, [sentinel])

Here,

  • object: Required. An iterable sequence. List, tuple, set, etc.
  • sentinel: Optional. If this is used, object must be callable.

Note: Without a second argument, object must be a collection object which supports the iteration protocol (the **__iter__()** method), or it must support the sequence protocol (the __getitem__() method with integer arguments starting at 0)

If it does not support either of those protocols, TypeError is raised. If the second argument, sentinel, is given, then o must be a callable object.

Examples

  • Without sentinel parameter
>>> i = iter([1, 2, 3])
>>> i.next()
1
>>> i.next()
2
>>> i.next()
3
>>> i.next()
Traceback (most recent call last):
  File "<interactive input>", line 1, in <module>
StopIteration
  • With custom object using sentinel parameter
class SquaredValue:

    def __init__(self):
        self.start = 1

    def __iter__(self):
        return self

    def __next__(self):
        self.start = self.start * 3
        return self.start

    __call__ = __next__
    
my_iter = iter(SquaredValue(), 729)

for x in my_iter:
    print(x)

Output:

3
9
27
81
243

Here, we used the sentinel parameter to stop the iteration. When the value from __next__() is equal to 729, then the program will stop.