How to use iter() in Python

The built-in Python function iter() is used to generate an iterator object. It can be used in conjunction with the next() function and loops, such as for or while loops. iter()uses lazy loading, which helps conserve memory especially when you only need to iterate through a part of a very large object.

Syntax

iter(object[, sentinel])

Parameters

The iter() function can take two parameters. The second parameter is optional.

  1. object: An object for which an iterator needs to be generated. If the second argument exists, it simply must be an object that can be called. If the second argument does not exist, the first argument must be a collection of objects with either an iteration or sequential protocol, like lists, sets, tuples, and dictionaries.

  2. sentinel: This is an optional argument. It marks the value where the iteration should stop. For example, if the value returns while the iteration is equal to the sentinel, the iteration stops.

Return value

An iterator object is returned.

Using next()

This function is used to return the next element in the iterator object. It takes one parameter: the iterator.

next(iterator)

If the element returned is equal to the sentinel or the iterator has been exhausted, the StopIteration exception is raised.

The iterator object that is generated can only be used to iterate through the object once. If you need to iterate through that object again, another iterator object needs to be generated.

Code

# declaring list
listObj = [1, 2, 3, 4]
listIterator = iter(listObj)
print("First iteration through list with iterator:")
while True:
try:
print(next(listIterator))
except StopIteration:
print("StopIteration Exception raised. End of iterator object.\n")
break
# trying to iterate through the list with the same iterator
# does not work
print("Second iteration through list with iterator:")
while True:
try:
print(next(listIterator))
except StopIteration:
print("StopIteration Exception raised. Trying to iterate through object with same iterator does not work")
break

Using the sentinel argument

# declare callable class
class takeSquare:
# constructor
def __init__(self, num):
self.num = num
def __call__(self):
# calling the class will return the square of num
self.num *= self.num
return self.num
# create iterator object and set sentinel
# when the function has been called the 4th time, the value
# returned will be equal to the sentinel value i.e. 65536
iterObj = iter(takeSquare(2), 65536)
# loop to iterate
while True:
try:
print(next(iterObj))
except StopIteration:
print("StopIteration Exception raised. Value returned was equal to sentinel value")
break

Free Resources