Python Iterator Method - iter()

The iter() method returns an iterator object that represents a stream of data for the iterable object or sentinel.

Syntax:

iter(object, sentinel)

Parameters:

  1. object: (Required) The object whose iterator should be created. If the second parameter sentinel is not specified, this object must be a collection object with the __iter__() method or the __getitem__() method with integer arguments starting at 0. If sentinel is given, then this must be a callable object. The __next__() function returns a value from the collection on each call.
  2. sentinel: (Optional) A value that indicates the end of sequence.

Return Value:

Returns an iterator object for the given object.

Iterators are implicitly used whenever we deal with collections of data types such as list, tuple or string (they are quite fittingly called iterables). The usual method to traverse a collection is using the for loop, as shown below.

Example:
nums = [1, 2, 3, 4, 5]
for item in nums:
    print(item)
Output
1 
2 
3 
4
5

In the above example, the for loop iterates over a list object- myList, and prints each individual element. When we use a for loop to traverse any iterable object, internally it uses the iter() method, same as below.

def traverse(iterable):
    it=iter(iterable)
    while True:
        try:
            item=next(it)
            print (item)
        except StopIteration:
            break

Instead of using the for loop as shown above, we can use the iterator function iter(). The iterator object uses the __next__() method. Every time it is called, the next element in the iterator stream is returned. When there are no more elements available, the StopIteration error is raised.

The following example demonstrates the iter() method.

Example: iter() and __next__()
nums = [1, 2, 3, 4, 5]
iter = iter(nums) # returns an iterator object

print(iter.__next__())) # calling __next__() to get the first element
print(iter.__next__())
print(iter.__next__())
print(iter.__next__())
print(iter.__next__())
print(iter.__next__()) # raise StopIteration error after last element
Output
1
2
3
4
5
Traceback (most recent call last):
itr.__next__()
StopIteration

In the above example, we specified a list collection object, so the iter() function returns the iterator object. Using the __next__() method of an iterator object, we can get each individual element of the collection. After returning the last element, it raises the StopIteration error.

You can use the next() method instead of __next__() method, as shown below.

Example: next()
nums = [1, 2, 3, 4, 5]
iter = iter(nums) # passing list object

print(next(iter))
print(next(iter))
print(next(iter))
print(next(iter))
print(next(iter))
print(next(iter)) # raise StopIteration error
Output
1
2
3
4
5
Traceback (most recent call last):
print(next(iter))
StopIteration

Implementing the __iter__() Method in Custom Class

The custom class can also be a collection class by implementing __iter__() and __next__() method to get an iterator object and use it with the for loop, as shown below.

Example:
class DataStore:
	def __init__(self, data):
		self.index = -1
		self.data = data
	def __iter__(self):
		return self
	def __next__(self):
		if(self.index == len(self.data)-1):
		    raise StopIteration
		self.index +=1
		return self.data[self.index]

ds = DataStore([1,2,3])
for i in ds:
	print(i)
Output
1
2
3

Using Sentinel Parameter

The sentinel parameter is used to indicate the end of the sequence. However, the class must be callable, which internally calls __next__() method. The following DataStore class is modified to demonstrate the use of the sentinel parameter by adding __call__ = __next__.

Example:
class DataStore:
	def __init__(self, data):
		self.index = -1
		self.data = data
	def __iter__(self):
		return self
	def __next__(self):
		if(self.index == len(self.data)-1):
		    raise StopIteration
		self.index +=1
		return self.data[self.index]
	__call__ = __next__
    
    ds = DataStore([1,2,3])
    itr = iter(ds, 3) # sentinel is 3, so it will stop when encounter 3
    
    for i in itr:
	    print(i)
Output
1
2