A variable in Python is a name bound to an object. Unlike languages such as C or Java, where a variable is a fixed-size box in memory, a Python variable is better understood as a label or sticky note attached to an object. The assignment statement x = 42 does not put the integer 42 into a box called x; it creates an integer object with value 42 and makes the name x refer to it. Multiple names can refer to the same object, and names can be rebound to different objects at any time.
This "names, not boxes" model has important consequences. Reassigning a variable does not modify the original object — it simply moves the label. Whether modifying an object through one name is visible through another depends on whether the object is mutable (like a list) or immutable (like an integer or string). Understanding this distinction is essential for avoiding aliasing bugs.
Variable names in Python must start with a letter or underscore and contain only letters, digits, and underscores. By convention, snake_case is used for variables and functions, UPPER_SNAKE_CASE for constants, and PascalCase for classes. Names beginning with an underscore carry special meaning: a single underscore suggests "internal use," and double underscores trigger name mangling in classes.
Related terms: Dynamic Typing, Mutable, Immutable, Scope
Discussed in:
- Chapter 3: Variables and Data Types — Names, Not Boxes