Recently, while doing some Python programming, I got the error as “Python local variable referenced before assignment“. I will show you here when I receive the error and how to fix this.
Local variable referenced before assignment in Python
I was working on a simple function in Python to count the number of times a specific word appears in a list of words. Here’s the initial code I wrote:
def count_word_occurrences(word_list, target_word):
count += 1
for word in word_list:
if word == target_word:
count += 1
return count
words = ["apple", "banana", "apple", "orange", "banana", "apple"]
print(count_word_occurrences(words, "apple"))
When I ran this code, I encountered the following error:
UnboundLocalError: local variable 'count' referenced before assignment
You can even see the exact error message in the screenshot below:

The error message indicates that I tried to use the local variable count before it was assigned a value. In Python, any variable assigned a value inside a function is considered local to that function. Since count was not initialized before being incremented, Python raised an UnboundLocalError.
Solution
Here is the solution for the above error.
To fix this error, I needed to initialize the count variable before using it. Here’s the corrected version of the function:
def count_word_occurrences(word_list, target_word):
count = 0 # Initialize the local variable
for word in word_list:
if word == target_word:
count += 1
return count
words = ["apple", "banana", "apple", "orange", "banana", "apple"]
print(count_word_occurrences(words, "apple"))
With this change, the count variable is initialized to 0 before the loop starts. This ensures that count has a value when it is incremented.
You can also see the output in the screenshot below; there is no error now.

Conclusion
The “local variable referenced before assignment” error is very common in Python due to its scoping rules. You need to ensure that variables are properly initialized before they are used; you can avoid this error. In this example, initializing the count variable solved the problem and allowed the function to execute correctly. In this tutorial, I have explained how to fix the error: “unboundlocalerror: local variable referenced before assignment in Python“.
You may also like the following tutorials:
- Local and Global Variables in Python
- Python Data Types
- Python Module Not Found After Pip Install
- How to Print Variable Names in a For Loop in Python?

I’m Michelle Gallagher, a Senior Python Developer at Lumenalta based in New York, United States. I have over nine years of experience in the field of Python development, machine learning, and artificial intelligence. My expertise lies in Python and its extensive ecosystem of libraries and frameworks. Throughout my career, I’ve had the pleasure of working on a variety of projects that have leveraged my skills in Python and machine learning. Read more…