Why can't I use yield with return?
I have a function that takes a list as input. The list can either be 1
item long or many items long.
If the list has only 1 item, I want my function to preform an operation on
that item and then return it.
However, if the list has multiple items, then I want my function to
preform the same operation on each of the items, but return them one by
one in a generator using yield. Below is a simplified example:
def func(lis):
if len(lis) == 1:
return lis[0] * 2
else:
for item in lis:
yield item * 2
When I run this code, I get the following error:
SyntaxError: 'return' with argument inside generator
I have ways to get around this, but running into this problem has made me
curious. Why can't I do this?
No comments:
Post a Comment