Python Tutorials
- Python
- How to install Python?
- PIP
- How to Run Python Program
- Python Identifiers,Statement, Indentation and Comments
- Variable
- Data type
- Decision Making
- Python Loops
- Break,Continue, Pass
- Functions
- Predefine Functions
- Lambda Functions
- Variable Scope
- List
- Tuple
- Python Sets
- Python Dictionary
- Python String
- String Formating
- Input/Output
- File Handling (Input / Output)
- Iterators
- Python Modules
- Python Date
- Python JSON
- Classes and Objects
- Constructor
- Polymorphism
- Encapsulation
- inheritance
- Class or Static Variables in Python
- class method vs static method
- Abstraction
- Exception Handling
- MySql Python
- MySql Create Database
- MySql CRUD
- Django
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)