Friday, March 6, 2020

Iterator and Iterable

Iterator and Iterable


What is iterable?


  • An iterable is an object that is able to return an iterator (an object with the countable number of elements).
  • An iterator object has the __next__() and the __iter__() methods.
  • An Iterator is an object that generates subsequent value during a sequence once we call next(*object*) on any object OR in other words, we can traverse entire iterable object with next() method.
  • An iterator raises StopIteration after exhausting the iterator and cannot be further re-used.
iterator python



For Example,

class DemoIterable:
     def __iter__(self):
          return self

     def __next__(self):
          #TO-DO

So, iterable is something that can be iterated with an iterator, for example, List, Sets, Tuples, and Dict. Our DemoIterable class objects are iterable. Now it is possible to iterate these objects.

ex1=DemoIterable()

for item in ex1:
      #DO-Something


The iter() method


We can get an iterator from iterable by iter() method.

t = (7, 3, 4)

i = iter(t)     # get iterator
print(next(i))         # 7
print(next(i))        # 3
print(next(i))        # 4
print(next(i))        #will raise StopIteration exception


String is iterable


The strings are the iterable objects, we can access all the characters in a string and iterate them.

s='python programming'
for i in s:
    print(i)


Creating an Iterator


We need to implement __iter__() and __next__() in the Iterator class.The StopIteration exception is raised when all elements are traversed. The __iter__() method acts similarly, we can do operations (initializing, etc.), but must always return the iterator object itself. The __next__() method also enables us to do operations and must return the next item in the sequence.



class DemoIterable:
       def __iter__(self): #iterator 
            self.start = 0
            return self

       def __next__(self): #next
            if self.start <= 50:
                a = self.start
                self.start += 5
                return a
           else:
               raise StopIteration #StopIteration

test = DemoIterable()
myiterator = iter(test)
for x in myiterator:
     print(x)

#Output:
0
5
10
15
20
25
30
35
40
45
50