Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get one value at a time from a generator function in Python?

People also ask

What is the value in using a generator in Python?

Python provides a generator to create your own iterator function. A generator is a special type of function which does not return a single value, instead, it returns an iterator object with a sequence of values. In a generator function, a yield statement is used rather than a return statement.

How do you print all the values of a generator in Python?

The short answer is that a generator expression cannot be printed because its values don't exist; they're generated on demand. What you can do (assuming the generator stops sometime) is get all the values out of it, like with list() , and then print them.

Can a generator be called multiple times in Python?

Yes, generator can be used only once.

What is yield in generator function Python?

What Is Yield In Python? The Yield keyword in Python is similar to a return statement used for returning values or objects in Python. However, there is a slight difference. The yield statement returns a generator object to the one who calls the function which contains yield, instead of simply returning a value.


Yes, or next(gen) in 2.6+.


In Python <= 2.5, use gen.next(). This will work for all Python 2.x versions, but not Python 3.x

In Python >= 2.6, use next(gen). This is a built in function, and is clearer. It will also work in Python 3.

Both of these end up calling a specially named function, next(), which can be overridden by subclassing. In Python 3, however, this function has been renamed to __next__(), to be consistent with other special functions.


Use (for python 3)

next(generator)

Here is an example

def fun(x):
    n = 0
    while n < x:
        yield n
        n += 1
z = fun(10)
next(z)
next(z)

should print

0
1

This is the correct way to do it.

You can also use next(gen).

http://docs.python.org/library/functions.html#next