Last modified: Mar 06, 2025 By Alexander Williams

Fix Python NameError: Name 'deque' Not Defined

If you're encountering the NameError: Name 'deque' Not Defined in Python, don't worry. This error is common and easy to fix. Let's dive into what causes it and how to resolve it.

What Causes the NameError: Name 'deque' Not Defined?

The NameError occurs when Python cannot find a name in your code. In this case, it can't find deque. This usually happens because you forgot to import the deque class from the collections module.

For example, if you try to use deque without importing it, you'll get this error:


# This will raise a NameError
my_queue = deque()


NameError: name 'deque' is not defined

How to Fix the NameError: Name 'deque' Not Defined

To fix this error, you need to import the deque class from the collections module. Here's how you can do it:


from collections import deque

# Now this will work
my_queue = deque()
print(my_queue)


deque([])

By importing deque, Python knows where to find it, and the error is resolved.

Common Mistakes to Avoid

Sometimes, even after importing, you might still encounter the error. Here are some common mistakes:

  • Typo in the import statement: Ensure you spell deque correctly.
  • Importing the wrong module: Make sure you import from collections, not another module.
  • Using deque before importing: Always import at the beginning of your script.

If you're facing similar errors with other Python objects, check out these guides:

Conclusion

The NameError: Name 'deque' Not Defined is a simple error to fix. Just import the deque class from the collections module. Always double-check your imports to avoid such issues. Happy coding!