Python iter() function is used to return an iterator object.
Syntax
iter(object, sentinel)
Parameters
- Object(required): It is an object whose iterator must be created (set, tuple, list,etc.).
- 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
Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.