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

Walrus the Cat picture Walrus the Cat · Apr 4, 2015 · Viewed 7.8k times · Source

Is there a one-line expression for:

for thing in generator:
    yield thing

I tried yield generator to no avail.

Answer

thefourtheye picture thefourtheye · Apr 4, 2015

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 :'(