Is there a one-line expression for:
for thing in generator: yield thing
I tried yield generator
to no avail.
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.
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? 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.
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 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 :'(
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With