python Iterators

python Iterators




Iterator in Python is simply an object that can be iterated upon. An object which will return data, one element at a time.

Technically speaking, a Python iterator object must implement two special methods, __iter__() and __next__(), collectively called the iterator protocol.

An object is called iterable if we can get an iterator from it. Most built-in containers in Python like: list, tuple, string etc. are iterables.

The iter() function (which in turn calls the __iter__() method) returns an iterator from them.
  • iter() and next() implementation 
list1 = ["mera", "naam", "joker", "mai", "joaqin", "pheonix"]
val = iter(list1) # iter() is inbuilt function returns object of iterable object

item = next(val) #next() is inbuilt function returns next item of iterable object
print(item)

item = next(val)
print(item)

item = next(val)
print(item)

item = next(val)
print(item)

item = next(val)
print(item)

item = next(val)
print(item)
  • iter(), next() and StopIteration implementation with while loop
list1 = ["mera", "naam", "joker", "mai", "joaqin", "pheonix"]
val = iter(list1) # iter() is inbuilt function returns object of iterable object
while True:  # this is internal working of for loop
    try:
item = next(val)
print(item)
except StopIteration: #stopIteration is used to catch exception
break
  • for loop uses while loop internally with iter, next and stopiteration function
list1 = ["mera", "naam", "joker", "mai", "joaqin", "pheonix"]
val = iter(list1) # iter() is inbuilt function returns object of iterable object
for i in list1:  # for loop implements iterators with the help of while loop internally
print("for loop", i)

Comments