Fixing Python NameError – name ‘List’ is not defined

Updated: February 14, 2024 By: Guest Contributor Post a comment

Understanding the Issue

Experiencing a NameError in Python, particularly one that mentions ‘List’ is not defined, can be a stumbling block for both newcomers and experienced developers alike. This error indicates the Python interpreter does not recognize ‘List’ as a defined name within your code’s current scope. There are several reasons why this could happen and various strategies to resolve the issue.

Possible Causes

This error typically occurs when Python’s built-in list type is attempted to be accessed with a capital ‘L’. Unlike some languages, Python is case-sensitive, meaning list and List are seen as fundamentally different identifiers. The error can also indicate a missed import statement if you’re trying to use a List type hint from the typing module.

Solutions to Fix the Issue

Solution #1: Correct Case Usage

One quick fix is to ensure you’re using the correct case. For instance, replace any mistaken usage of ‘List’ with the lower-case ‘list’ for creating lists. If you’re dealing with type hints, ensure you’ve properly imported the List from the typing module.

  1. Identify where the NameError is thrown in your code.
  2. Replace any uppercase ‘L’ in ‘List’ with a lowercase ‘l’ for creating list objects or ensure correct import statement for type hints.
  3. Run your code again to verify the issue is resolved.

Code Example:

# Creating a list
my_list = ['apple', 'banana', 'cherry']

# Using List as a type hint (correct case)
from typing import List

my_list_hinted: List[str] = ['apple', 'banana', 'cherry']

Notes: Correcting case usage is a simple yet effective solution. It does not require any fundamental changes to the logic or structure of your code. However, it necessitates careful attention to detail, especially in more complex projects.

Solution #2: Importing Required Module

If your error pertains to using List for type annotations, it’s crucial to check whether you have imported the List type from the typing module. Without the correct import statement, Python will not recognize List as a valid name.

  1. Check if the error message points to a line where you’re using List for a type hint.
  2. Confirm if the typing module’s List type has been correctly imported at the top of your file.
  3. Add the import statement if it’s missing.
  4. Re-run your code to ensure the error is rectified.

Code Example:

# Assuming you forgot to import List initially
from typing import List

my_annotation: List[int] = [1, 2, 3]

Notes: This solution is imperative for modern Python practices, especially with the emphasis on type hinting for better code clarity and type-checking support. While importing necessary modules adds an extra line at the top of your file, it ensures your code utilizes Python’s full functionality and adheres to best practices.