python iter() method

Python iter() method

The python iter() method is used to return an iterable object. An iterable can be a Python list, Python tuple, etc.

Python iter() function

Python iter() method Syntax :

iterableObject= iter(object, sentinel)

object: which needs to be converted to iterable.

sentinel: This is an optional argument. It represents the end of an iterator.

iter() method Examples in python

Below are the different types of examples.

Example 1:

Tup=('a','b','c','d')
obj=iter(Tup)
print(obj)


Output :

<tuple_iterator object at 0x000002823865E640>

As you can see iter() method returns an object. For traversing an iterable using an iter() method, we use a next() method with the iterable object.

Example 2:

Tup=('a','b','c','d')
obj=iter(Tup)
print(obj)
print(next(obj))
print(next(obj))
print(next(obj))
print(next(obj))


Output :

<tuple_iterator object at 0x00000235A83AE640>
a
b
c
d 

According to the above output, next() will return an element one by one. Therefore, next() is used to iterate the values. After traversing all the elements, it raises a StopIteration exception.

Example 3:

l=['a','b','c','d']
obj=iter(l)
print(obj)
print(next(obj))
print(next(obj))
print(next(obj))
print(next(obj))
print(next(obj))


Output :

Traceback (most recent call last):
  File "E:\Python files">
    print(next(obj))
StopIteration
<list_iterator object at 0x000001A814854FD0>
a
b
c
d

We can also use Python for loop to iterate.

Example 4:

l=['a','b','c','d']
n= len(l)
obj=iter(l)
for i in range(0,n,1):
    print(next(obj))


Output :

a
b
c
d

Discover Our Exciting Courses and Quiz

Enroll now to enhance your skills and knowledge!

Python Online Quiz

Level up your coding skills with our interactive programming quiz!