SyntaxError: 'yield' outside function in Python

avatar

Borislav Hadzhiev

Last updated: Apr 25, 2022

banner

Photo from Unsplash

SyntaxError: 'yield' outside function in Python #

The Python "SyntaxError: 'yield' outside function" occurs when we use the yield keyword outside of a function. To solve the error, use a list comprehension if you need to perform some operator for every element, or indent the code that uses yield inside of a function.

syntaxerror yield outside function

Here is an example of how the error occurs.

main.py
for i in range(5): # ⛔️ SyntaxError: 'yield' outside function yield i + 10

We cannot use the yield keyword outside a function.

One way to get around this is to use a list comprehension.

main.py
my_list = [i + 10 for i in range(5)] print(my_list) # 👉️ [10, 11, 12, 13, 14]

The list comprehension in the example adds 10 to each item in the range 0-4.

You can also use a generator expression.

main.py
my_gen = (i + 10 for i in range(5)) print(my_gen) # 👉️ <generator object <genexpr> at 0x7f76a5974660> my_list = list(my_gen) print(my_list) # 👉️ [10, 11, 12, 13, 14]
Generator expressions and list comprehensions are used to perform some operation for every element or select a subset of elements that meet a condition.

If you have a generator function, make sure the code that uses the yield keyword is indented correctly.

main.py
def g(): yield 1 yield 2 yield 3 gen = g() for i in gen: print(i) # 👉️ 1, 2, 3

The example shows how to iterate over a generator using a for loop.

Alternatively, you can pass the generator to the next() function to retrieve the next item.

main.py
def g(): yield 1 yield 2 yield 3 gen = g() print(next(gen)) # 👉️ 1 print(next(gen)) # 👉️ 2 print(next(gen)) # 👉️ 3

If you need to convert a generator object to a list, pass it to the list() class.

main.py
def g(): yield 1 yield 2 yield 3 # 👇️ convert to list my_list = list(g()) print(my_list) # 👉️ [1, 2, 3] print(len(my_list)) # 👉️ 3

Note that once the generator is converted to a list, it is exhausted.

main.py
def g(): yield 1 yield 2 yield 3 # 👇️ convert to list gen = g() print(list(gen)) # 👉️ [1, 2, 3] print(list(gen)) # 👉️ []

This is why you have to convert the generator to a list and store the result in a variable.

Conclusion #

The Python "SyntaxError: 'yield' outside function" occurs when we use the yield keyword outside of a function. To solve the error, use a list comprehension if you need to perform some operator for every element, or indent the code that uses yield inside of a function.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.