Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any shorthand for 'yield all the output from a generator'?

Is there a one-line expression for:

for thing in generator:     yield thing 

I tried yield generator to no avail.

like image 348
Walrus the Cat Avatar asked Apr 04 '15 10:04

Walrus the Cat


People also ask

What is generator yield?

The yield keyword pauses generator function execution and the value of the expression following the yield keyword is returned to the generator's caller. It can be thought of as a generator-based version of the return keyword. yield can only be called directly from the generator function that contains it.

What takes place when a generator function calls yield?

When you call a function that contains a yield statement anywhere, you get a generator object, but no code runs. Then each time you extract an object from the generator, Python executes code in the function until it comes to a yield statement, then pauses and delivers the object.

What does the yield keyword do?

What does the yield keyword do? Yield is a keyword in Python that is used to return from a function without destroying the states of its local variable and when the function is called, the execution starts from the last yield statement. Any function that contains a yield keyword is termed a generator.

What is the return type of a generator?

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.


2 Answers

In Python 3.3+, you can use yield from. For example,

>>> def get_squares(): ...     yield from (num ** 2 for num in range(10)) ...  >>> list(get_squares()) [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] 

It can actually be used with any iterable. For example,

>>> def get_numbers(): ...     yield from range(10) ...  >>> list(get_numbers()) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> def get_squares(): ...     yield from [num ** 2 for num in range(10)] ...  >>> list(get_squares()) [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] 

Unfortunately, Python 2.7 has no equivalent construct :'(

like image 63
thefourtheye Avatar answered Sep 22 '22 10:09

thefourtheye


You can use a list comprehension to get all of the elements out of a generator (assuming the generator ends):

[x for x in generator] 
like image 29
Ramón J Romero y Vigil Avatar answered Sep 24 '22 10:09

Ramón J Romero y Vigil