r/pythonhelp • u/AmongstYou666 • Jun 28 '22
Invalid syntax trying to yield one-line for loop
def yield_array(ar):
for r in row_range:
for c in col_range:
yield(ar[r][c])
[print(ar[r][c]) for r in row_range for c in col_range]
[yield(ar[r][c]) for r in row_range for c in col_range] # invalid syntax?
3
Upvotes
3
u/carcigenicate Jun 28 '22 edited Jun 28 '22
The almost-equivalent code is just:
yield_array = (ar[r][c] for r in row_range for c in col_range)With a generator expression, whatever is on the left is yielded.
3
u/Goobyalus Jun 28 '22 edited Jun 28 '22
In the list comprehension
the part before the
formust be an expression.yield <expression>is a statement, not an expression, so it is invalid.Edit: To add, it's not a "one-line for loop". This is special syntax for creating an object, that happens to iterate like a for loop. E.g.
[print(x) for x in range(10)]will create the object[None, None, None, None, None, None, None, None, None, None].