1

I came across these terms iterables, generator and yield while solving the following problem which uses the yield keyword:

question: Define a class with a generator which can iterate the numbers, which are divisible by 7, between a given range 0 and n.

Solution:

def putNumbers(n):
    i = 0
    while i<n:
        j=i
        i=i+1
        if j%7==0:
            yield j
        for i in reverse(100):
            print i

I didn't understand why yield is used here. I have gone through this source to also understand.

and raise one more question since both the code for iterables and generators gives same output.

code for iterables:

mylist = [x*x for x in range(3)]
for i in mylist:
    print(i)

code for generator:

mygenerator = [x*x for x in range(3)]
for i in mygenerator:
    print(i)

then what is the significance?

Community
  • 1
  • 1
Vinit Jain
  • 21
  • 1

0 Answers0