Is there a one-line expression for:
for thing in generator:
yield thing
I tried yield generator
to no avail.
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 :'(
yield from
does in Py3.3. Calling this function just returns another generator object, so it is pretty similar to the built-in iter
. If you call your yield_from()
from within a function, this function will not automatically become a generator function, as will happen with yield from
. As far as I understand, in Py2.7, you need to write the explicit for-loop as shown by the OP.
Apr 4, 2015 at 11:47
for i in generator: yield i
can not be factored out into a separate function. You just rewrote iter
... :)
Apr 4, 2015 at 11:51
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]
Here is a simple one-liner valid in Python 2.5+ as requested ;-):
for thing in generator: yield thing