Python iter()

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

Example


iter() Syntax

The syntax of the iter() method is:

iter(object, sentinel [optional])

iter() Parameters

The iter() method takes two parameters:

  • object - can be a list, set, tuple, etc.
  • sentinel [optional] - a special value that is used to represent the end of a sequence

iter() Return Value

The iter() method returns:

  • iterator object for the given argument until the sentinel character is found
  • TypeError for a user-defined object that doesn't implement __iter__(), and __next__() or __getitem()__

Example 1: Python iter()

Output

a
e
i
o
u

In the above example, we have used the iter() method with a list of vowels.

The method returns the individual elements a, e, i, o, u in the list as the iterator objects.


Example 2: iter() for custom objects

Output

1
2
3
Traceback (most recent call last):
  File "", line 23, in 
File "", line 11, in __next__
StopIteration

In the example above, we have printed the iterator numbers 1,2, 3 using the __iter__() and __next__() methods.

Here, the __next()__ method here has a loop that runs till self.num is greater than or equal to self.max .

Since we have passed 3 as the parameter to the PrintNumber() object, self.max is initialized to 3. Therefore, the loop stops at 3.

When self.num reaches the value of self.max which is 3, the next() method raises a StopIteration exception.


Example 3: iter() with Sentinel Parameter

Output

2
4
8

In the above example, we haven't implemented a StopIteration condition.

Instead, we have used the iter() method with a sentinel parameter to stop the iteration:

my_iter = iter(DoubleIt(), 16)

The value of the sentinel parameter here is 16 so the program will stop when the value from the __next__() method is equal to this number.

At this point in the code, the program will raise a StopIteration automatically.


Recommended Reading: