Alex
Alex

Reputation: 44385

What does 'yield' return if no argument is given?

There are some examples of python functions that contains a yield - but without any parameter.

Examples: here and here and here.

So what does that yield yield then? How does it work?

Upvotes: 6

Views: 2640

Answers (1)

icc97
icc97

Reputation: 12833

So what does that yield yield then?

As commented by Paul Becotte yield without a value yields None.

How does it work?

From the Python Generators wiki, the yield syntax is the syntactic sugar that you need to tell Python to generate an iterable object from your function. It converts:

# a generator that yields items instead of returning a list
def firstn(n):
    num = 0
    while num < n:
        yield num
        num += 1

into:

# Using the generator pattern (an iterable)
class firstn(object):
    def __init__(self, n):
        self.n = n
        self.num, self.nums = 0, []

    def __iter__(self):
        return self

    # Python 3 compatibility
    def __next__(self):
        return self.next()

    def next(self):
        if self.num < self.n:
            cur, self.num = self.num, self.num+1
            return cur
        else:
            raise StopIteration()

So I could just remove it? — comment

Without the yield keyword it's just a function that returns None.

Carrying on further down in the wiki, there is a way that you can create iterators without the yield keyword. You use list comprehension syntax with (). So to carry on the rather trivial example (which is just xrange, the generator version of range):

def firstn(n):
    return (x for x in range(n)) 

Alternately, we can think of list comprehensions as generator expressions wrapped in a list constructor.

>>> list(firstn(10))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> [x for x in range(10)]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Upvotes: 5

Related Questions