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?
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 one, and 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__() technique, we 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:
- Python Hello World Program
- Python Comment | Creating a Comment | multiline comment | example
- Python Dictionary Introduction | Why to use dictionary | with example
- How to do Sum or Addition in python
- Python Reverse number
- find the common number in python
- addition of number using for loop and providing user input data in python
- Python Count char in String
- Python Last Character from String
- Python Odd and Even | if the condition
- Python Greater or equal number
- Python PALINDROME NUMBER
- Python FIBONACCI SERIES
- Python Dictionary | Items method | Definition and usage
- Python Dictionary | Add data, POP, pop item, update method
- Python Dictionary | update() method
- Delete statement, Looping in the list In Python
- Odd and Even using Append in python
- Python | Simple Odd and Even number
Get Salesforce Answers