Python iter()

The iter() method returns an iterator for the given object.

The iter() method creates an object which can be iterated one element at a time.

These objects are useful when coupled with loops like for loop, while loop.

The syntax of iter() method is:

iter(object[, sentinel])

Recommended Reading: Python iterators and how to work with them.


iter() Parameters

The iter() method takes two parameters:

  • object - object whose iterator has to be created (can be sets, tuples, etc.)
  • sentinel (Optional) - special value that is used to represent the end of a sequence

Depending upon the arguments passed, iter() must have the following attributes.

Different cases for iter() parameters
Object Sentinel Description
Collection object (set, tuple) None Creates iterator for the collection object
User defined object (Custom object) None Either:
  • implement __iter__() and __next__() methods
  • implement __getitem__() method with integer arguments starting at 0
User defined object (Custom object) which doesn't implement __iter__() and __next() OR __getitem__() None Raises TypeError exception
Callable object Provided Returns iterator that calls object with no arguments for each call to its __next__() method If sentinel found, raises StopIteration exception

Return value from iter()

The iter() method returns iterator object for the given object that loops through each element in the object.

In case of sentinel provided, it returns the iterator object that calls the callable object until the sentinel character isn't found.


Example 1: How iter() works in Python?

# list of vowels
vowels = ['a', 'e', 'i', 'o', 'u']

vowelsIter = iter(vowels)

# prints 'a'
print(next(vowelsIter))

# prints 'e'
print(next(vowelsIter))

# prints 'i'
print(next(vowelsIter))

# prints 'o'
print(next(vowelsIter))

# prints 'u'
print(next(vowelsIter))

When you run the program, the output will be:

a
e
i
o
u

Example 2: How iter() works for custom objects?

class PrintNumber:
    def __init__(self, max):
        self.max = max

    def __iter__(self):
        self.num = 0
        return self

    def __next__(self):
        if(self.num >= self.max):
            raise StopIteration
        self.num += 1
        return self.num

printNum = PrintNumber(3)

printNumIter = iter(printNum)

# prints '1'
print(next(printNumIter))

# prints '2'
print(next(printNumIter))

# prints '3'
print(next(printNumIter))

# raises StopIteration
print(next(printNumIter))

When you run the program, the output will be:

1
2
3
StopIteration

Example 3: How iter() works for callable objects with sentinel?

with open('mydata.txt') as fp:
    for line in iter(fp.readline, ''):
        processLine(line)

When you run the program, it will open mydata.txt in read mode.

Then, the iter(fp.readline, '') in the for loop calls readline (which reads each line in the text file) until the sentinel character '' (empty string) is reached.