Skip to main content
A Python variable is a symbolic identifier bound to an object in memory. Unlike variables in statically typed languages, which act as typed memory containers, Python variables are untyped references (or pointers) to objects. The data type is associated strictly with the object itself, not the variable referencing it.

Assignment and Binding

Variables are created and bound to objects using the assignment operator (=). This operation evaluates the expression on the right side to instantiate an object in memory, and then binds the identifier on the left side to that object’s memory address.
Because Python is dynamically typed, a single variable can be reassigned to objects of entirely different types during runtime without structural conflict or memory reallocation of the identifier.

Memory and Reference Mechanics

When multiple variables are assigned the same value, Python may bind them to the same object in memory to optimize resources (a process known as interning). You can inspect the memory address of the underlying object using the built-in id() function, and verify object identity using the is operator.
Python utilizes reference counting as its primary memory management mechanism. Every time a variable is bound to an object, that object’s reference count increments. When a variable is reassigned or goes out of scope, the count decrements. If an object’s reference count drops to zero, the allocated memory is immediately reclaimed. Additionally, Python employs a cyclic garbage collector designed specifically to detect and clean up reference cycles (isolated groups of objects referencing each other) that reference counting alone cannot resolve.

Identifier Rules

Variable names must adhere to strict lexical rules enforced by the Python parser:
  • Allowed Characters: Can contain alphanumeric characters, underscores (_), and natively supported Unicode characters (e.g., A-Z, a-z, 0-9, π, é).
  • Prefix Constraints: Cannot begin with a numeric digit.
  • Case Sensitivity: Variable and variable represent distinct, independent references.
  • Reserved Words: Cannot conflict with Python’s built-in keywords (e.g., class, return, def, yield).

Scope and Namespace

A variable’s accessibility is determined by its scope, which dictates the specific namespace where the identifier-to-object binding exists. Python resolves variable scope hierarchically using the LEGB rule:
  1. Local: Bound within the current function or method.
  2. Enclosing: Bound within the local scope of any enclosing functions (used in closures).
  3. Global: Bound at the top level of a script or module.
  4. Built-in: Pre-assigned in Python’s built-in namespace (e.g., len, Exception).
Tired of Poor Python Skills? Fix That With Deep Grasping!Learn More