Python iter() Function

Python iter() function is used to return an iterator object.

Using iter() Function

Syntax

iter(object, sentinel)

Parameters

  1. Object(required): It is an object whose iterator must be created (settuple, list,etc.).
  2. sentinel(0ptional) – It is the special value used to represent the termination of a sequence.

Return value

It returns an iterator object that yields values until it encounters a value equal to the sentinel.

Example 1: Passing Single Parameter

# Create a list of strings
str_list = ['millie', 'finn', 'gaten', 'caleb']

# Create an iterator object from the list
my_iter = iter(str_list)

# Using next() to get the next item from the iterator
print(next(my_iter))
print(next(my_iter)) 
print(next(my_iter))
print(next(my_iter)) 

Output

millie
finn
gaten
caleb

Example 2: Passing Sentinel Parameter

import random

def generate_random():
 return random.randint(1, 10)

# Iterates until generate_random returns 5
random_iter = iter(generate_random, 5)

for num in random_iter:
 print(num)

Output

8
8
10
10
3

Example 3: TypeError: ‘NonIterable’ object is not iterable

If you try to use the iter() function on a user-defined object that doesn’t implement either the __iter__() and __next__() methods (for the iterator protocol) or the __getitem__() method (for the sequence protocol), it will raise a TypeError.

class NonIterable:
  pass

obj = NonIterable()

try:
 iter_obj = iter(obj)
except TypeError as e:
 print(f"TypeError: {e}")

Output

TypeError: 'NonIterable' object is not iterable

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.