What is Python Iterators?

An iterator is an object that can be iterated upon, meaning that you can traverse through all the values.

Technically, in Python, an iterator is an object which implements the iterator protocol, which consist of the methods __iter__() and __next__()

Iterator vs Iterable

Lists, tuples, dictionaries, and sets are all iterable objects. They are iterable containers which you can get an iterator from

All these objects have a iter() method which is used to get an iterator:

File name : index.py

mytuple = ("Mahtab", "Sana", "Sara")
myit = iter(mytuple)

print(next(myit))
print(next(myit))
print(next(myit))


output :-


Mahtab
sana
sara

Even strings are iterable objects, and can return an iterator:

File name : index.py

mystr = "mahtab"
myit = iter(mystr)

print(next(myit))
print(next(myit))
print(next(myit))
print(next(myit))
print(next(myit))
print(next(myit))


output :-

m
a
h
t
a
b

Looping Through an Iterator

File name : index.py

mytuple = ("apple", "banana", "cherry")

for x in mytuple:
print(x)

Iterate the characters of a string:

File name : index.py

mystr = "banana"

for x in mystr:
print(x)

Create an Iterator

To create an object/class as an iterator you have to implement the methods __iter__() and __next__() to your object.

File name : index.py

class MyNumbers:
def __iter__(self):
self.a = 1
return self

def __next__(self):
x = self.a
self.a += 1
return x

myclass = MyNumbers()
myiter = iter(myclass)

print(next(myiter))
print(next(myiter))
print(next(myiter))
print(next(myiter))
print(next(myiter))

StopIteration

To prevent the iteration to go on forever, we can use the StopIteration statement.

File name : index.py

class MyNumbers:
def __iter__(self):
self.a = 1
return self

def __next__(self):
if self.a <= 20:
x = self.a
self.a += 1
return x
else:
raise StopIteration

myclass = MyNumbers()
myiter = iter(myclass)

for x in myiter:
print(x)





Previous Next


Trending Tutorials




Review & Rating

0.0 / 5

0 Review

5
(0)

4
(0)

3
(0)

2
(0)

1
(0)

Write Review Here