Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is for/while loop from python is a generator

In an interview , the interviewer asked me for some of generators being used in Python. I know a generator is like a function which yield values instead of return.

so any one tell me is for/while loop is an example of generator.

like image 621
Sanjay Avatar asked Jun 13 '17 08:06

Sanjay


2 Answers

Short answer: No, but there are other forms of generators.

A for/while loop is a loop structure: it does not emit values and thus is not a generator.

Nevertheless, there are other ways to construct generators.

You example with yield is for instance a generator:

def some_generator(xs):
    for x in xs:
        if x:
            yield x

But there are also generator expressions, like:

(x for x in xs if x)

Furthermore in python-3.x the range(..), map(..), filter(..) constructs are generators as well.

And of course you can make an iterable (by using an iterable pattern):

class some_generator(object):
    def __init__(self, xs):
        self.n = n
        self.idx = 0

    def __iter__(self):
        return self

    def __next__(self):
        return self.next()

    def next(self):
        while self.num < len(self.xs) and not self.xs[self.num]:
            self.num += 1
        if self.num < len(self.xs):
            res = self.xs[self.num]
            self.num += 1
            return res
        else:
            raise StopIteration()
like image 200
Willem Van Onsem Avatar answered Oct 20 '22 13:10

Willem Van Onsem


Neither while nor for are themselves generators or iterators. They are control constructs that perform iteration. Certainly, you can use for or while to iterate over the items yielded by a generator, and you can use for or while to perform iteration inside the code of a generator. But neither of those facts make for or while generators.

like image 5
PM 2Ring Avatar answered Oct 20 '22 13:10

PM 2Ring