Python iter()

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

Example

# list of vowels
phones = ['apple', 'samsung', 'oneplus']
phones_iter = iter(phones)

print(next(phones_iter))   
print(next(phones_iter))    
print(next(phones_iter))    

# Output:
# apple
# samsung
# oneplus

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()

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

# iter() with a list of vowels vowels_iter = iter(vowels)
print(next(vowels_iter)) print(next(vowels_iter)) print(next(vowels_iter)) print(next(vowels_iter)) print(next(vowels_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

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

# iter() method in a class def __iter__(self): self.num = 0
return self
# next() method in a class def __next__(self): if(self.num >= self.max): raise StopIteration
self.num += 1 return self.num print_num = PrintNumber(3) print_num_iter = iter(print_num) print(next(print_num_iter)) # 1 print(next(print_num_iter)) # 2 print(next(print_num_iter)) # 3
# raises StopIteration print(next(print_num_iter))

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

class DoubleIt:

    def __init__(self):
        self.start = 1

    def __iter__(self):
        return self

    def __next__(self):
        self.start *= 2
        return self.start

    __call__ = __next__
    
my_iter = iter(DoubleIt(), 16)

for x in my_iter:
    print(x)

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:

Did you find this article helpful?