Can generator be used to create iterators in Python?


Yes, We can create a generator by using iterators in python Creating iterators is easy, we can create a generator by using the keyword yield statement. 

Python generators are an easy and simple way of creating iterators. and is mainly used to declare a function that behaves like an iterator.

The generator is a function which we can iterate over one value at a time most probably in a day to day life, every programmer will use iterable objects like lists, strings, and Dict, etc. 

An iterator is an object that can be iterated through looping.

The following example shows that Generators introduce Yield statement in python it works like returning a value.

Example

def generator():
   print("program working sucessfully")
   yield 'x'
   yield 'y'
   yield 'z'
generator()

Output

<generator object generator at 0x000000CF81D07390>

By using for loop also we can create a generator

Example

for i in generator():
print(i)

Output

program working sucessfully
x
y
z


iterators objects support two methods 1.__iter__method and  2.__next__method

  The __iter__ method returns the iterator object itself. mainly it is used for loop and in statements. 

  The __next__ method returns the next value from the iterator if no more items return it should raise StopIteration Exception.

Example

class function(object):
   def __init__(self, lowtemp, hightemp):
      self.current = lowtemp
      self.high = hightemp
   def __iter__(self):
      'Returns itself as an iterator object'
      return self
   def __next__(self):
      'Returns the next value till current is lower than high'
      if self.current > self.high:
         raise StopIteration
      else:
         self.current += 1
         return self.current - 1
c = function(3,20)
for i in c:
print(i, end=' ')

Output

3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20

Sri
Sri

Updated on: 30-Jul-2019

234 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements