Iterator and Iterables in Python
Let us know difference between Iterable and Iterator
Iterables
Iterables object is the one which acts like loop and you can iterate own elements. It can directly used on lops like strings, List, Tuple, Set, Dictionary and Generator.
Anything on for loop is iterables.
from typing import Iterable, Iterator
# Iterable
# a=[]{}()’’90
# print(isinstance(a,Iterable))a=[1,2,3,4,5,6]
print(“List “,isinstance(a,Iterable))
for x in a:
print(x)b=(10,20,30,40,50,60)
print(“Tuple “,isinstance(b,Iterable))
for x in b:
print(x)c={11,22,33,44,55,66}
print(“Set “,isinstance(c,Iterable))
for x in c:
print(x)d=”Naren Coder033"
print(“String “,isinstance(d,Iterable))
for x in d:
print(x)
On above example you can see we are iterates List, Tuple, Set and Strings.
Iterator
Iterator produce a value during the iteration and returning iterable object. The process of iterator based on __iter__( ) and __next__( ). On last you should raise the Stop Iteration because when the is no value after list then at that time you should set Stop Iteration.
Get Narayanan’s stories in your inbox
Join Medium for free to get updates from this writer.
Anything on next() is iterator.
lista=iter([1,2,3,4,5])print(isinstance(lista,Iterator))
print(lista)
print(next(lista))
print(next(lista))
print(next(lista))
print(next(lista))
print(next(lista))
# print(next(lista)) Stop iteration pop up error
On above we are iterated a list element using next element and on final when there is no next element it will raise error.
At first __iter__() function will return an iterator which that value inside iterator are accessed using __next__() function. Each and every call of __next__() function the value on iterator will give a value from list.
Iterator implemented on while loop
alpha=iter([‘a’,’b’,’c’,’d’,’e’])
while True:
try:
x=next(alpha)
print(x)
except StopIteration:
breakOn above example we are initiated StopIteration using while loop.
File Iterator
On same directory create a txt file as fileio.txt
welcome
to
the
worldon python app.py file
txt=open(‘./fileio.txt’)
print(txt)# for x in txt:
# print(x)res=iter(txt)# print(res.__next__())
# print(res.__next__())# --- You can initiate using while method ---while True:
try:
y=next(res)
print(y)
except StopIteration:
break
Class based Iterator
Basically the process of iterator is is based on Class. Iterator has finite or infinite on sequences, in order to achieve those value we use next function, on calling of next element it return next value and wait for triggering point on triggering it return another value. So the process is lazy computation process.
class add:
limit=10
def __init__(self,x):
self.x=x
def __iter__(self):
return self
def __next__(self):
self.x+=1
if self.x<self.limit:
return self.x
raise StopIterationcheck=add(1)
print(check)for val in check:
print(val)
In above example we are initiated class based iterator and we declared __iter__() and __next__() on function as well as we raised StopIteration and it returned values and those value are printed using for loop.
Another example for Iterator
class loop_list:
a=0
def __init__(self,x):
self.x=x
self.len=len(x)
def __iter__(self):
return self
def __next__(self):
if self.a>self.len-1:
raise StopIteration
op=self.x[self.a]
self.a+=1
return opalpha=[‘a’,’b’,’c’,’d’,’e’]
result=loop_list(alpha)
print(result)for val in result:
print(val)
Here on above example we sent loop of values to iterator process and those value are returned and printed using for loop.
Follow for more interesting topics :-)
Follow us on
Instagram:- https://www.instagram.com/Coder_033/
Github:- https://github.com/Coder033
Skillshare:- https://www.skillshare.com/profile/Coder033/26410885 Youtube:-https://www.youtube.com/channel/UCjTUcwOms1NJDo2UiIvGfyg









