Python iter() function “returns an iterator for the given argument.”
Syntax
iter(object, sentinel)
Parameters
- Object: It is an object whose iterator must be created (set, tuple, list, dictionary, etc.).
- sentinel (Optional) – It is the special value used to represent the end of a sequence.
Return value
The iter() method returns:
- It is an 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: How to Use Python iter() Method
data = iter(['millie', 'finn', 'gaten', 'caleb'])
print(next(data))
print(next(data))
print(next(data))
print(next(data))
We passed a list to the iter() function in the above code and printed the item using the next() function.
Example 2: Using the custom project
Define the custom object and then iterate that object using the next() function.
class Display:
def __init__(self, count):
self.count = count
def __iter__(self):
self.data = 0
return self
def __next__(self):
if(self.data >= self.count):
raise StopIteration
self.data += 1
return self.data
num = Display(2)
printData = iter(num)
# prints '1'
print(next(printData))
# prints '2'
print(next(printData))
# raises StopIteration
print(next(printData))
Output
1
2
Traceback (most recent call last):
File "app.py", line 26, in <module>
print(next(printData))
File "app.py", line 11, in __next__
raise StopIteration
StopIteration
Example 3: Python iter() with Sentinel Parameter
class HelloBro:
def __init__(self):
self.start = 1
def __iter__(self):
return self
def __next__(self):
self.start *= 2
return self.start
__call__ = __next__
main_iter = iter(HelloBro(), 16)
for x in main_iter:
print(x)
That’s it.

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.