Is there an abbreviation for "getting all the output from the generator"?

Is there a single line expression for:

for thing in generator: yield thing 

I tried yield generator no avail.

+6
source share
3 answers

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

 >>> 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 be used with any iterable. For instance,

 >>> 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 does not have an equivalent construct: '(

+9
source

You can use list comprehension to get all the elements from the generator (assuming the end of the generator):

 [x for x in generator] 
+2
source

Here is a simple one-line key valid in Python 2.5+ on request; -):

 for thing in generator: yield thing 
+1
source

Source: https://habr.com/ru/post/984679/


All Articles