Skip to main content

Variables and Naming

Topic — In Python, variable names are identifiers that bind names to objects stored in memory. While the interpreter strictly rejects syntax errors like leading digits or hyphens, the greater danger lies in naming anti-patterns: accidentally shadowing built-in functions like list or sum without realizing it. This guide covers legal identifier syntax, the 35 reserved keywords, PEP 8 styling conventions, and the memory pointer model.


1. The Core Concept​

An identifier is a token used to name a variable, function, class, or module. In Python:

StatusRuleExample
AllowedMust start with a letter (a-z, A-Z) or an underscore (_)student, _private
AllowedCan contain letters, digits (0-9), and underscoresuser_123, batch_size
AllowedCase-sensitive (age, Age, AGE are 3 separate variables)age != Age != AGE
ForbiddenCannot start with a digit2fast (SyntaxError)
ForbiddenCannot contain spacesstudent name (SyntaxError)
ForbiddenCannot contain hyphens or symbols (-, @, #, $, %)my-var, total$
ForbiddenCannot be a Python keywordclass, for, def
WarningShould never shadow built-ins (list, str, dict, sum)list = [1, 2] (Breaks list())
tip

If you only take one thing from this page

In Python, - is the subtraction operator, not a separator. Writing student-name is parsed as student minus name, raising SyntaxError: cannot assign to expression. Always use underscores (student_name).


2. Interactive Variable Name Validator​

Type any candidate identifier into the input box below or click the preset buttons to check syntax legality, keyword collisions, built-in shadowing, and PEP 8 compliance live:

Python Variable Name Validator

Type a candidate variable name or test one of the common problem presets:

VALID PYTHON IDENTIFIERStyle: snake_case (Variables and Functions)

Legal Python identifier adhering to standard PEP 8 snake_case.


3. Python's 35 Reserved Keywords​

Python 3.11 features 35 reserved keywords. These are hardcoded into the language grammar and cannot be assigned as variable names:

CategoryReserved Keywords
Control Flowif, elif, else, for, while, break, continue, pass
Functions & Classesdef, return, lambda, yield, class
Imports & Modulesimport, from, as
Exception Handlingtry, except, finally, raise, assert
Logic & Identityand, or, not, in, is
ConstantsTrue, False, None
Scope & Memoryglobal, nonlocal, del
Asynchronous & Contextwith, async, await
note

Soft Keywords

Python 3.10 introduced "soft keywords" (match, case, type, and _). These act as keywords inside pattern matching statements, but remain syntactically legal as variable names elsewhere. However, using them as variables confuses collaborators and linters; avoid them.


4. The Silent Hazard: Shadowing Built-ins​

Unlike keywords, Python's built-in functions (list, str, int, dict, sum, id, type, input, min, max) are not reserved syntax tokens.

Assigning list = [1, 2, 3] is syntactically legal. However, doing so shadows the built-in function in the local namespace:

# THE SHADOWING TRAP
list = [1, 2, 3] # Legal, but 'list' now references an array instance!

# Later in your codebase:
new_items = list((4, 5))
# TypeError: 'list' object is not callable
danger

Why Shadowing is Worse than a SyntaxError

A SyntaxError prevents your program from starting immediately. Built-in shadowing compiles cleanly and fails silently much later in unrelated modules when another function attempts to call str(), sum(), or list().


5. Interactive Memory Pointer Model​

Variables in Python are named labels pointing to objects on the heap, not physical boxes containing data:

Memory Pointer and Object Identity Simulator

Select a scenario to visualize how variables reference objects in memory:

Mutable List Aliasing (Shared Object Reference)
a = [1, 2, 3]
b = a          # Both labels point to memory address 0x7f9a
b.append(99)   # Modifies the object in-place!
print(a)       # Output: [1, 2, 3, 99]
Label a
Points to [1, 2, 3, 99]
Label b
Points to [1, 2, 3, 99]

Memory Mechanism: Because lists are mutable, b = a does not duplicate the list. Both variable names point to the exact same heap memory location (a is b == True).


6. Implementation Lab​

tip

Lab Exercise: Identifiers, Built-in Shadowing & Memory Aliasing

An interactive, fully functional Google Colab / Jupyter Notebook is available to validate identifiers programmatically using keyword.iskeyword() and str.isidentifier(), inspect memory addresses with id(), and reproduce built-in shadowing live in your browser.

Open In Colab

How to run the lab:

  1. Click the "Open In Colab" badge above to launch the interactive notebook.
  2. Run cells sequentially to test identifier validation rules and memory aliasing.

Key Experiments to Run:

  • Experiment 1 (Programmatic Legality): Iterate over 10 candidate names using str.isidentifier() and keyword.iskeyword().
  • Experiment 2 (The Built-in Shadowing Crash): Assign a variable sum = 300 and observe the subsequent TypeError when attempting to call sum([10, 20]). Restore the function using del sum.
  • Experiment 3 (Object Identity with id()): Inspect hex(id(a)) and hex(id(b)) to empirically verify shared heap references.

7. Common Mistakes​


  • The Misconception: "HTML and CSS use user-name, so Python allows it."
  • Wrong Thinking: Typing user-name = "Alex".
  • The Right Principle: - is the subtraction operator. Python evaluates user minus name = "Alex", which raises SyntaxError: cannot assign to expression. Always use underscores (user_name).

8. Summary​

Syntactic Rules

  • Valid First Character: Letter (a-z, A-Z) or underscore (_).
  • Subsequent Characters: Letters, digits (0-9), and underscores.
  • Forbidden: Digits first, spaces, hyphens (-), symbols (@, $).
  • Reserved: 35 Python grammar keywords (class, def, for).

PEP 8 Style Conventions

  • snake_case: Variables and functions (student_name, calc_total).
  • UPPER_CASE: Constants (MAX_RETRIES, DEFAULT_TIMEOUT).
  • PascalCase: Classes (StudentProfile, LinearModel).
  • _leading: Internal / private scope hint (_hidden_state).

info

Key Takeaways

  • Variables are pointers: Assignment binds a label to an object; mutable objects can be altered via any shared alias tag.
  • Never shadow built-ins: Avoid using list, str, dict, sum, id, type, or input as variable names.
  • Follow PEP 8: Use descriptive snake_case names rather than single-letter acronyms.

Next Section: Data Types - exploring the full catalog of Python's built-in numeric, sequence, mapping, and set data types.


9. Active Recall​

Test your understanding by answering first, then clicking to reveal the underlying principles.

Interactive Checkpoint Quiz​

Interactive Checkpoint: Identifying the Illegal Identifier

Which of the following variable assignments will cause an immediate Python SyntaxError?

Review Flashcards​

1. [THEORY] Why does Python raise a SyntaxError on student-name = "Alex", but a NameError on student#name = "Alex"?

  • Hyphen (-): Is parsed as the binary subtraction operator. Python sees an expression assignment (student minus name = ...), which is illegal syntax.
  • Hash (#): Marks the start of a code comment! Python completely ignores everything after # on that line, executing only student.
  • Because student has never been defined, Python raises NameError: name 'student' is not defined.
2. [PRACTICE] What happens when you run sum = 100 followed by sum([1, 2, 3])? How do you fix it?

  • The Crash: TypeError: 'int' object is not callable.
  • Assigning sum = 100 binds the name sum to an integer object in your local namespace, shadowing the built-in function.
  • Attempting to call sum(...) now treats the integer 100 as a function!
  • The Fix: Delete the variable from the namespace: del sum. This restores access to the global built-in function.
3. [THEORY] What does the is operator test compared to == in Python?

  • == tests Value Equality: Does object A hold the same contents as object B?
  • is tests Reference Identity: Do labels A and B point to the exact same object at the same memory address (id(A) == id(B))?
  • Example: [1, 2] == [1, 2] is True, but [1, 2] is [1, 2] is False (two distinct list instances).
4. [ANALYZE] Does Python have true constants like C++ const or JavaScript const?

  • No: Python has no language construct to prevent variable reassignment.
  • Writing MAX_USERS = 100 is purely a PEP 8 signaling convention to human developers that the variable should not be changed.
  • If a developer executes MAX_USERS = 200, the interpreter rebinds the variable without any error.
5. [THEORY] Why are leading underscores used in variable names like _cache?

  • PEP 8 Privacy Convention: A single leading underscore signals to other developers and IDEs that the variable or method is intended for internal use only.
  • Wildcard Import Protection: Names with a leading underscore are not imported when another module executes from my_module import *.