In Python 3 you can use str.isidentifier() to test whether a given string is a valid Python identifier/name.

>>> 'X'.isidentifier()
True
>>> 'X123'.isidentifier()
True
>>> '2'.isidentifier()
False
>>> 'while'.isidentifier()
True

The last example shows that you should also check whether the variable name clashes with a Python keyword:

>>> from keyword import iskeyword
>>> iskeyword('X')
False
>>> iskeyword('while')
True

So you could put that together in a function:

from keyword import iskeyword

def is_valid_variable_name(name):
    return name.isidentifier() and not iskeyword(name)

Another option, which works in Python 2 and 3, is to use the ast module:

from ast import parse

def is_valid_variable_name(name):
    try:
        parse('{} = None'.format(name))
        return True
    except SyntaxError, ValueError, TypeError:
        return False

>>> is_valid_variable_name('X')
True
>>> is_valid_variable_name('123')
False
>>> is_valid_variable_name('for')
False
>>> is_valid_variable_name('')
False
>>> is_valid_variable_name(42)
False

This will parse the assignment statement without actually executing it. It will pick up invalid identifiers as well as attempts to assign to a keyword. In the above code None is an arbitrary value to assign to the given name - it could be any valid expression for the RHS.

Answer from mhawke on Stack Overflow
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-variables
Python Variables - GeeksforGeeks
Below listed variable names are valid: Python · age = 21 _colour = "lilac" total_score = 90 · Below listed variables names are invalid: Python · 1name = "Error" # Starts with a digit class = 10 # 'class' is a reserved keyword user-name = "Doe" # Contains a hyphen ·
Published   2 weeks ago
🌐
W3Schools
w3schools.com › python › python_variables_names.asp
Python - Variable Names
Python Examples Python Compiler ... ... A variable can have a short name (like x and y) or a more descriptive name (age, carname, total_volume)....
Top answer
1 of 6
65

In Python 3 you can use str.isidentifier() to test whether a given string is a valid Python identifier/name.

>>> 'X'.isidentifier()
True
>>> 'X123'.isidentifier()
True
>>> '2'.isidentifier()
False
>>> 'while'.isidentifier()
True

The last example shows that you should also check whether the variable name clashes with a Python keyword:

>>> from keyword import iskeyword
>>> iskeyword('X')
False
>>> iskeyword('while')
True

So you could put that together in a function:

from keyword import iskeyword

def is_valid_variable_name(name):
    return name.isidentifier() and not iskeyword(name)

Another option, which works in Python 2 and 3, is to use the ast module:

from ast import parse

def is_valid_variable_name(name):
    try:
        parse('{} = None'.format(name))
        return True
    except SyntaxError, ValueError, TypeError:
        return False

>>> is_valid_variable_name('X')
True
>>> is_valid_variable_name('123')
False
>>> is_valid_variable_name('for')
False
>>> is_valid_variable_name('')
False
>>> is_valid_variable_name(42)
False

This will parse the assignment statement without actually executing it. It will pick up invalid identifiers as well as attempts to assign to a keyword. In the above code None is an arbitrary value to assign to the given name - it could be any valid expression for the RHS.

2 of 6
3

EDIT: this is wrong and implementation dependent - see comments.

Just have Python do its own check by making a dictionary with the variable holding the name as the key and splatting it as keyword arguments:

def _dummy_function(**kwargs):
    pass

def is_valid_variable_name(name):
    try:
        _dummy_function(**{name: None})
        return True
    except TypeError:
        return False

Notably, TypeError is consistently raised whenever a dict splats into keyword arguments but has a key which isn't a valid function argument, and whenever a dict literal is being constructed with an invalid key, so this will work correctly on anything you pass to it.

🌐
Quora
quora.com › What-are-the-valid-variable-names-in-Python
What are the valid variable names in Python? - Quora
Examples of valid identifiers: x, _x, var1, π, résumé, σ2 · Examples of invalid identifiers: 1var (starts with digit), my-var (hyphen), class (reserved keyword) Reserved keywords (cannot be used as variable names) — Python 3.12+ (common ...
🌐
Real Python
realpython.com › python-variables
Variables in Python: Usage and Best Practices – Real Python
January 12, 2025 - These variables follow the rules for creating valid variable names in Python. They also follow best naming practices, which you’ll learn about in the next section. The variable name below doesn’t follow the rules: ... >>> 1099_filed = False File "<input>", line 1 1099_filed = False ^ SyntaxError: invalid decimal literal · The variable name in this example ...
🌐
Apmonitor
apmonitor.com › che263 › index.php › Main › PythonBasics
Python Programming Basics
Valid variable names are those that start with a letter (upper or lower case) or underscore. Valid variable names include: myVar myVariable my4Variable myVariable4 _myVariable __myVariable MYVARIABLE myvariable · Invalid variable names include those that start with a number, have a space in ...
🌐
MAKE ME ANALYST
makemeanalyst.com › home › python programming › python variable names and keywords
Python Variable Names and Keywords - MAKE ME ANALYST
December 10, 2017 - So, variable1 is valid while 1variable is a invalid name. You may use uppercase letters for variable names but it is always perfectly fine to begin variable names with a lowercase letter. If your Variable name is long, then you can use underscore character (_) in the name. For example, top_five_members, var_1 ...
Find elsewhere
🌐
Reddit
reddit.com › r/learnpython › where can i find a list of which variable names to avoid
r/learnpython on Reddit: Where can I find a list of which variable names to avoid
October 16, 2022 -

I found lists of "reserved keywords" for python, but there seems to be other words which python lets you use for variable names, but maybe it's better not to use these names?

Such as 'file' or 'sum,' etc

Is there a complete list of such words?

🌐
Tutorial Teacher
tutorialsteacher.com › python › python-variables
Python Variables: A Beginner's Guide to Declaring, Assigning, and Naming Variables in Python
The variable name can consist of alphabet letter(s), number(s) and underscore(s) only. For example, myVar, MyVar, _myVar, MyVar123 are valid variable names, but m*var, my-var, 1myVar are invalid variable names. Variable names in Python are case ...
🌐
Learn with Yasir
yasirbhutta.github.io › python › docs › variables › variables-basics.html
Python Variables Explained: Basics, Naming Rules & Practical Examples | Learn with Yasir
Python has 35 reserved keywords (e.g., if, for, while). ... | Valid ✅ | Invalid ❌ | |——————-|——————–| | user_name | user-name (hyphen)| | _total | 2nd_place (starts with digit)| | price2 | class (reserved keyword)|
🌐
W3Resource
w3resource.com › python-interview › what-are-variables-in-python-rules-for-naming-variables-in-python.php
Python variables: Definition, assignment, and naming rules
August 12, 2023 - The convention is to use lowercase letters for variable names, with underscores (_) to separate words in multi-word variable names (snake_case). For example, my_variable, student_age, total_amount, item_price. Here are some examples of valid ...
🌐
Note.nkmk.me
note.nkmk.me › home › python
Valid Variable Names and Naming Rules in Python | note.nkmk.me
May 5, 2023 - 2. Lexical analysis - Keywords — Python 3.11.3 documentation · Note that isidentifier() returns True for reserved words and keywords since they are valid strings. However, using them as identifiers (variable names, function names, class names, etc.) will raise an error. print('None'.isidentifier()) # True # None = 100 # SyntaxError: can't assign to keyword ... To get a list of keywords and check if a string is a keyword, use the keyword module of the standard library.
🌐
Codefinity
codefinity.com › courses › v2 › 2f60173b-9829-4c84-8548-85bf65183f71 › 984eb7ed-25b1-40e1-93d0-3f7991547ac9 › 9078d240-0669-41e4-a40c-9e4538c36fad
Learn Variable Naming Rules | Variables and Types
For example `item_name` is a valid variable print = 5.0 # You cannot use reserved keywords as a variable # But you can use these words in combination with others to name a variable # For example, `print_quantity = 5.0` is valid.
🌐
Dydevops
dydevops.com › tutorials › python › python-variable-names
Python - Variable Names Explained with Examples - Python Tutorial | DyDevOps
May 20, 2025 - Variable names are case-sensitive (name and Name are different). Cannot use Python keywords (e.g., class, if, else, True, etc.). ... 1user = "Invalid" # Starts with a digit user-name = "Error" # Hyphen is not allowed class = "Python" # 'class' is a reserved keyword
🌐
Unstop
unstop.com › home › blog › identifiers in python: rules, examples, & best practices
Identifiers In Python: Rules, Examples, & Best Practices
May 7, 2025 - Pro Tip: Good names should describe what the variable stores, not the whole story. Example: x = 100 # ✅ valid but vague total_amount = 100 # ✅ valid and descriptive totalAmountUserPaid...
🌐
Runestone Academy
runestone.academy › ns › books › published › py4e-int › variables › variable-names-keywords.html
2.3. Variable names and keywords — Python for Everybody - Interactive
The variable name 76trombones is illegal because it begins with a number. The name more@ is illegal because it contains an illegal character, @. But what’s wrong with class? It turns out that class is one of Python’s keywords.
🌐
Sanfoundry
sanfoundry.com › python-questions-answers-variable-names
Variable Names - Python Questions and Answers - Sanfoundry
December 30, 2025 - Answer: b Explanation: In Python, variable names cannot have spaces between them, so a b c = 1000 2000 3000 is invalid syntax. 10. Which of the following cannot be a variable name in Python? a) __init__ b) in c) it d) on View Answer · Answer: ...
🌐
Brainly
brainly.com › computers and technology › high school › which of the following is not a valid variable in python? a. _var b. var_name c. var11 d. 5var
[FREE] Which of the following is not a valid variable in Python? a. _var b. var_name c. var11 d. 5var - brainly.com
Examples of valid variable names include '_var', 'var_name', and 'var11', while '5var' is an invalid name because it starts with a number. Python's official documentation outlines the rules for valid variable naming, which clearly states that ...