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.
iter(object[, sentinel])
The iter()
function can take two parameters. The second parameter is optional.
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.
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.
An iterator object is returned.
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.
# declaring listlistObj = [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 workprint("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
sentinel
argument# declare callable classclass takeSquare:# constructordef __init__(self, num):self.num = numdef __call__(self):# calling the class will return the square of numself.num *= self.numreturn 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. 65536iterObj = iter(takeSquare(2), 65536)# loop to iteratewhile True:try:print(next(iterObj))except StopIteration:print("StopIteration Exception raised. Value returned was equal to sentinel value")break