What are iterators and generators in Python?

What are Python iterators?

An iterator is an associate object that contains a numerable range of values.

An iterator is an associate object which will be iterated upon, which means that you just will traverse through all the values.

Technically, in Python, the associate iterator is an associate object that implements the iterator protocol, that accommodates the ways __iter__() and __next__().

What is the difference between iterator and iterable in python?

Lists, tuples, dictionaries, and sets are all iterable objects. They’re iterable containers that you’ll be able to get an associate iterator from Ghostwriter Agentur. One way to utilize these containers is through

Python iterators

Return associative iterator from a tuple, and print every value:

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

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

Output:

C:\Users\Pramod\PycharmProjects\pythonProject\venv\Scripts\python.exe C:/Users/Pramod/PycharmProjects/pythonProject/main.py
apple
banana
cherry

Process finished with exit code 0

Even strings are iterable objects, and may come associate iterator:

Strings also are iterable objects, containing a sequence of characters:

mystr = "Pramod"
myiter = iter(mystr)

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

Output:

C:\Users\Pramod\PycharmProjects\pythonProject\venv\Scripts\python.exe C:/Users/Pramod/PycharmProjects/pythonProject/main.py
P
r
a
m
o
d

Process finished with exit code 0

Looping Through associate Iterator

We can additionally use a for loop to retell through an associate iterable object:

Iterate the values of a tuple:

mytuple = ("coconut", "papaya", "mango")

for x in mytuple:
print(x)

Output:

C:\Users\Pramod\PycharmProjects\pythonProject\venv\Scripts\python.exe C:/Users/Pramod/PycharmProjects/pythonProject/main.py
coconut
papaya
mango

Process finished with exit code 0

Iterate the characters of a string:

mystr = "Coconut"

for x in mystr:
print(x)

Output:

C:\Users\Pramod\PycharmProjects\pythonProject\venv\Scripts\python.exe C:/Users/Pramod/PycharmProjects/pythonProject/main.py
C
o
c
o
n
u
t

Process finished with exit code 0

The for loop really creates an associate iterator object and executes the next() technique for every loop

How to Create Iterator in Python

  • To create an associate object/class as an associate iterator you’ve got to implement the ways __iter__() and __next__() to your object.
  • As you’ve got learned within the Python Classes/Objects chapter, all categories have a perform referred to as__init__(), which permits you are doing some initializing once the thing is being created.
  • The __iter__() technique acts similar, you’ll be able to do operations (initializing, etc.), however, should come the iterator object itself.
  • The __next__() technique addition all permits you to try and do operations and should come following item within the sequence.

Example

Create an associate iterator that returns numbers, beginning with oneand every sequence can increase by one (returning 1,2,3,4,5, etc.):

class MyNumbers:


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


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

myclass = MyNumbers()
myit = iter(myclass)

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

Output:

C:\Users\Pramod\PycharmProjects\pythonProject\venv\Scripts\python.exe C:/Users/Pramod/PycharmProjects/pythonProject/main.py
1
2
3
4
5
6
7

Process finished with exit code 0

StopIteration in Python

  • The example on top of would continue forever if you had enough next() statements, or if it absolutely was employed in a for a loop.
  • To prevent the iteration to travel on forever, we will use the StopIteration statement.
  • In the __next__() techniquewe will add a terminating condition to lift mistake if the iteration is completed a nominative range of times:

StopIteration Example

class MyNumbers:


def __iter__(self):
self.x = 1
return self


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

myclass = MyNumbers()
myit = iter(myclass)

for num in myit:
print(num)

Output:

C:\Users\Pramod\PycharmProjects\pythonProject\venv\Scripts\python.exe C:/Users/Pramod/PycharmProjects/pythonProject/main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

Process finished with exit code 0

 

Recommended Post:

Get Salesforce Answers

Pramod Kumar Yadav is from Janakpur Dham, Nepal. He was born on December 23, 1994, and has one elder brother and two elder sisters. He completed his education at various schools and colleges in Nepal and completed a degree in Computer Science Engineering from MITS in Andhra Pradesh, India. Pramod has worked as the owner of RC Educational Foundation Pvt Ltd, a teacher, and an Educational Consultant, and is currently working as an Engineer and Digital Marketer.



Leave a Comment