Python iter() function

Published February 16, 2022

The iter() function in Python is used to return the iterator of the specified object. This method generates an object that can be iterated over one element at a time. These items are essential in loops and while loops.

The Syntax
The iter() has the following simple  syntax()

iter(object, sentinel)

Where:
Object: This is the object that will be iterated over.
Sentinel: these are the values that will represent the end of the sequence.


Example

x = [5, 4, 3, 2, 1]
print("The type of the list is : " + str(type(x)))
y = iter(x)
print("The type of iterator is : " + str(type(y)))
print(next(y))
print(next(y))
print(next(y))
print(next(y))
print(next(y))

Output

The type of the list is : <class 'list'>
The type of iterator is : <class 'list_iterator'>
5
4
3
2
1
>

 

 

Download Source code

 

Article Contributed By :
https://www.rrtutors.com/site_assets/profile/assets/img/avataaars.svg

429 Views