Table of Contents
The Python iter() function returns an iterator for the given object.
The iter()
function creates an object which can be iterated one element at a time.
These objects are useful when coupled with loops like for loop, while loop.
The syntax of the iter()
function is:
iter(object, sentinel)
1. iter() Parameters
The iter()
function takes two parameters:
- object – object whose iterator has to be created (can be sets, tuples, etc.)
- sentinel (optional) – special value that is used to represent the end of a sequence
2. Return value from iter()
- The
iter()
function returns an iterator object for the given object. - If the user-defined object doesn’t implement
__iter__()
, and__next__()
or__getitem()__
, theTypeError
exception is raised. - If the sentinel parameter is also provided,
iter()
returns an iterator until the sentinel character isn’t found.
3. Example 1: Working of Python iter()
# list of vowels vowels = ['a', 'e', 'i', 'o', 'u'] vowels_iter = iter(vowels) print(next(vowels_iter)) # 'a' print(next(vowels_iter)) # 'e' print(next(vowels_iter)) # 'i' print(next(vowels_iter)) # 'o' print(next(vowels_iter)) # 'u'
Output
a e i o u
4. Example 2: iter() for custom objects
class PrintNumber: def __init__(self, max): self.max = max def __iter__(self): self.num = 0 return self 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
5. 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
Here, we have implemented a custom iterable object without a StopIteration
condition.
However, we can use the iter()
method with the sentinel
parameter to stop the iteration. If the value returned from __next__()
is equal to sentinel
, StopIteration
will be raised, otherwise, the value will be returned.
Recommended Reading: Python Iterators
Related posts:
Python isinstance()
Python Artificial Intelligence Project for Beginners - Joshua Eckroth
Python Deeper Insights into Machine Learning - Sebastian Raschka & David Julian & John Hearty
Python exec()
Python Program to Shuffle Deck of Cards
Python Set symmetric_difference_update()
Python String isdecimal()
Python Program to Trim Whitespace From a String
Python Set isdisjoint()
Python Program to Convert Two Lists Into a Dictionary
Python Program to Copy a File
Python datetime
Python Program to Convert Bytes to a String
Python Program to Concatenate Two Lists
Python strptime()
Python Program to Count the Number of Digits Present In a Number
Python String startswith()
Python frozenset()
Python Program to Reverse a Number
Machine Learning with Python for everyone - Mark E.Fenner
Python input()
Python Program to Calculate the Area of a Triangle
Python Program to Create a Long Multiline String
Python zip()
Python Dictionary items()
Python Object Oriented Programming
Python object()
Python sum()
Building Chatbots with Python Using Natural Language Processing and Machine Learning - Sumit Raj
Python Program to Display Fibonacci Sequence Using Recursion
Python Anonymous / Lambda Function
Deep Learning with Applications Using Python - Navin Kumar Manaswi