This guide deals with the Python iter function and it’s uses, complete with several examples.

The Python iter() function takes as input an object and returns an iterable object. This iterable object is useless on its own, but when used with something like a for loop or while loop, it becomes a powerful weapon. The iterable object it creates can be iterated over one element at a time.


Syntax

The iter object takes up-to parameters as input, object and sentinel.

iter(object, sentinel)
  1. object is the object of which the iterable object is required. Typically examples are lists and tuples. This parameter is compulsory
  2. The sentinel has a unique position in the iter function. Just like its name implies, it’s like a ‘sentinel’ watching over the function. The sentinel is basically a special value that is used to represent the end of a sequence. See examples below.

We’ll be using the next() function to proceed to the next element in the iter objects. Be sure to check out the next() function as well.


Example Set 1:

We’ll be trying this first set without the use of sentinel. We can expect to receive the StopIteration error when the sequence is exceeded.

lis = ['a','b','c','d','e']

X = iter(lis)
print(next(X))
print(next(X))
print(next(X))
print(next(X))
print(next(X))
print(next(X))
a
b
c
d
e
Traceback (most recent call last):
  File "C:\Users\Shado\Desktop\DIEEE.py", line 11, in <module>
    print(next(X))
StopIteration

Example Set 2:

This time we will be using the sentinel parameter. This way, an exception won’t be thrown and program execution will proceed normally.

lis = ['a','b','c','d','e']

X = iter(lis)
print(next(X, "End"))
print(next(X, "End"))
print(next(X, "End"))
print(next(X, "End"))
print(next(X, "End"))
print(next(X, "End"))
a
b
c
d
e
End

This marks the end of the Python iter Function Article. Any suggestions or contributions for CodersLegacy are more than welcome. Questions can be asked in the comment section below.

Here’s a link back to the main Python Built-in Functions page.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments