PythonPython Variables and Data TypesPython variables
What are variables in Python?
Question 30 of 88 · Updated
On this page
- 1. How does a variable work in Python?
- 2. Variable names, values, objects and types
- 3. Dynamic typing and rebinding
- 4. Multiple variables can refer to one object
- 5. Rebinding a name is different from mutating an object
- 6. What happens before a variable receives a value?
- 7. Where can a variable be accessed?
- 8. What happens when you delete a variable?
- 9. Do type annotations change how variables work?
- 10. Practical example: using variables to calculate a shopping-cart total
- 11. Common mistakes
- 12. Frequently asked questions
- Does Python require declaring variables before assignment?
- Can a variable change its type?
- Are variables and objects the same?
- Is assigning one variable to another the same as copying?
- Is None the same as an uninitialized variable?
- Can a name exist without an assigned value?
- Interview-ready answer
- Key takeaways
- Official references
A variable in Python is a name bound to an object. You use variables to refer to values, perform calculations, maintain program state and pass information between parts of a program. Unlike languages that require an explicitly declared storage type for every ordinary variable, Python permits names to be bound and rebound to objects of different types at runtime.
For example:
PYTHONquantity = 3 price = 120 print(quantity * price)
Output:
360The names quantity and price refer to integer objects. The multiplication expression retrieves the values associated with those names and computes the result.
This example uses whole monetary units for simplicity. Real billing applications may require a specified currency, decimal arithmetic and rounding rules.
1. How does a variable work in Python?#
Consider the assignment score = 10. Python evaluates the expression on the right and binds the name on the left to the resulting object.
Name Object
score ------------> integer 10A later assignment can change which object the name refers to.
PYTHONscore = 10 score = score + 5 print(score)
Output:
15Python evaluates score + 5 using the existing binding before assigning the result back to score. The name is rebound to an integer object representing 15. The original integer object representing 10 is not modified.
A variable is therefore better understood as a named reference to an object than as a fixed-size box that physically contains the value. The precise representation of names and references is implementation-dependent.
2. Variable names, values, objects and types#
These terms describe related but distinct concepts.
| Term | Meaning |
|---|---|
| Identifier | A syntactically valid name, such as quantity |
| Variable | A name used to refer to an object through a binding |
| Object | A Python entity with identity, type and value |
| Type | Determines supported operations and other object behaviour |
| Assignment | Establishes or updates a binding, attribute or item, depending on its target |
The earlier identifiers lesson explains naming syntax, keywords and Unicode rules. Here the emphasis is what names refer to and how assignments affect those references.
Not all identifiers are used as ordinary variables. Identifiers also appear in class definitions, function names, parameters and attribute access.
3. Dynamic typing and rebinding#
Objects have types. Ordinary Python names do not have a permanently enforced runtime type.
PYTHONvalue = 42 print(type(value).__name__) value = 'ready' print(type(value).__name__)
Output:
int
strInitially, value refers to an integer object. The next assignment binds it to a string object. The integer has not been converted into a string; the name now refers to a different object.
This flexibility does not mean that all operations between objects are permitted. Python still enforces the rules of the operation being executed. A program that attempts an unsupported operation can raise TypeError.
For maintainable code, avoid repeatedly repurposing a variable for unrelated kinds of information merely because the language allows it. A consistent role and meaningful name often make a program easier to understand.
4. Multiple variables can refer to one object#
Assignment to a name does not generally copy the object.
PYTHONa = [10, 20] b = a b.append(30) print(a) print(a is b)
Output:
[10, 20, 30]
TrueBoth a and b refer to the same list.
a ----+
+----> list [10, 20, 30]
b ----+The append operation modifies that shared list. Both names can observe the change because they refer to the same object. This relationship is commonly called aliasing.
The is operator tests object identity. It is not interchangeable with equality (==), which asks objects to compare their values according to their equality behaviour.
If you need an independent list, create an appropriate copy. A shallow copy duplicates the outer list but may retain references to nested objects. A deep copy is another option when appropriate, but may cost more and does not make every object suitable for copying.
5. Rebinding a name is different from mutating an object#
Compare the preceding example with a different assignment:
PYTHONa = [10, 20] b = a b = [99] print(a) print(b)
Output:
[10, 20]
[99]This time, b is rebound to a new list. The original list remains unchanged, and a still refers to it.
a ----------> list [10, 20]
b ----------> list [99]The distinction is important for debugging applications that maintain shared state.
For immutable objects such as integers, an arithmetic operation produces a result rather than modifying the original integer object:
PYTHONx = 5 y = x x = x + 1 print(x, y)
Output:
6 5The assignment changes the binding of x, not the value associated with y.
Avoid reasoning about Python variable behaviour using assumptions about memory addresses or integer caching. Object identity is the language-level concept; allocation and caching details can vary between implementations.
6. What happens before a variable receives a value?#
Ordinary Python assignment establishes a binding when the statement executes. Reading a name for which no binding can be found raises NameError.
For example, if missing_name has never been defined in the relevant environment, the expression print(missing_name) raises NameError.
If a value is deliberately not yet available, a developer can explicitly assign None:
PYTHONstatus = None print(status is None)
Output:
TrueThis is an initialized name bound to the None singleton. It is not an undefined variable.
Use None only when absence is meaningful to the program, and handle that state before performing operations requiring another type. Python does not automatically initialize ordinary variables to zero or None.
7. Where can a variable be accessed?#
A variable's visibility depends on its scope. For a simple example:
PYTHONcount = 0 def report(): count = 3 print(count) report() print(count)
Output:
3
0The assignment inside report creates a local binding. The module-level count retains its earlier value.
A name can have different bindings in different scopes. Python has rules for resolving local, enclosing, global and built-in names in common function contexts. Class scopes and some other contexts have additional rules.
When Python determines that a name is local to a function, attempting to read it before it has received a value can raise UnboundLocalError, a subclass of NameError. For example, a function containing print(x) followed by x = 1 will raise that error if the first statement runs before the assignment.
Prefer passing required values as function arguments and returning results rather than relying on unnecessary global state. Detailed scope resolution is a separate topic later in the curriculum.
8. What happens when you delete a variable?#
Deleting an ordinary name removes that binding. It does not necessarily destroy the referenced object.
PYTHONitems = [1, 2] other = items del items print(other)
Output:
[1, 2]The other binding still refers to the list. Trying to read items afterward in the same scope would fail unless another valid binding is available.
An object may become eligible for reclamation after it is no longer reachable, subject to the Python implementation's memory-management rules. CPython uses reference counting together with cyclic garbage collection, but code should not assume that all implementations reclaim objects at the same time.
For resources such as open files, use the relevant explicit cleanup mechanism or a context manager rather than depending on name deletion or garbage collection.
9. Do type annotations change how variables work?#
Python supports annotations that describe expected types.
PYTHONquantity: int = 3 quantity = 'three' print(quantity)
Output when executed as ordinary Python:
threeA static type checker would normally flag the incompatible second assignment. Python itself does not enforce an ordinary variable's annotation automatically in this example.
An annotation without an assignment does not necessarily bind a value. At module level, writing x: int alone does not initialize x; reading x before any binding exists can raise NameError.
Annotations improve documentation and help static analysis, but they are not a substitute for runtime validation of external input. Frameworks or other tools may implement their own validation using annotations.
10. Practical example: using variables to calculate a shopping-cart total#
PYTHONdef cart_total(unit_prices): total = 0 for price in unit_prices: total += price return total print(cart_total([120, 80, 100])) print(cart_total([]))
Output:
300
0The parameter unit_prices refers to the supplied collection. The local variable total accumulates the running result, and price refers to each successive element as the loop executes.
The initial value of zero is deliberate: it is the additive identity and gives a sensible result for an empty collection. Without initialization, the first attempt to read total would fail.
For n items, this example uses O(n) arithmetic operations and O(1) auxiliary space under the conventional fixed-size numeric cost model, excluding the input and output. Python integers can grow in size, so arithmetic cost is not strictly constant for arbitrarily large values.
The example assumes integer prices in a single monetary unit. It does not implement currency conversion, validation or production financial rounding.
11. Common mistakes#
| Mistake | Explanation |
|---|---|
| Reading a name before it has been bound | Can raise NameError or UnboundLocalError |
| Assuming b = a copies a list | Both names can refer to the same mutable object |
| Confusing assignment and equality | = assigns; == performs an equality comparison |
| Assuming annotations enforce runtime types | Ordinary annotations do not automatically validate assignments |
| Using None as if it were a number | Absence must be handled before numeric operations |
| Shadowing a built-in name | Naming a variable list or sum can hide a useful built-in in that scope |
| Assuming del destroys an object immediately | Other references may keep the object alive |
Use descriptive names such as order_total rather than unrelated single-letter names. Short names can still be appropriate in compact mathematical expressions or conventional loop counters.
Choose variable lifetimes and scopes that reflect the responsibilities of the program. Avoid keeping mutable objects in shared global state unless the design requires it and access is appropriately controlled.
12. Frequently asked questions#
Does Python require declaring variables before assignment?#
No separate type declaration is required for ordinary assignment. An assignment such as score = 10 binds the name when it executes.
Can a variable change its type?#
More precisely, a variable can be rebound to an object of another type. The objects themselves have types.
Are variables and objects the same?#
No. A variable is a name binding; an object is the entity to which that binding refers. Multiple names may refer to the same object.
Is assigning one variable to another the same as copying?#
No. For ordinary name assignment, the target name is bound to the resulting object. Use a suitable copying operation when an independent object is needed.
Is None the same as an uninitialized variable?#
No. None is a real singleton object. A name assigned None has a binding; an undefined name does not.
Can a name exist without an assigned value?#
A name may appear in an annotation or other source construct without having a usable runtime binding. Do not assume an annotation initializes the variable.
Interview-ready answer#
A Python variable is a name bound to an object. Ordinary assignment evaluates the right-hand expression and binds the target name to its result, without requiring an explicit type declaration. Python is dynamically typed, so names can be rebound to objects of different types. Multiple variables can refer to the same mutable object, making mutation different from rebinding. Variable access depends on scope, and reading a name before it is bound can raise NameError or UnboundLocalError. Type annotations help documentation and static analysis but do not automatically enforce runtime assignment types.
Key takeaways#
- Names refer to objects; objects have identity, type and value.
- Assignment to an ordinary name binds or rebinds it.
- Assigning a reference is not the same as copying an object.
- Mutation affects a shared mutable object, whereas rebinding changes a name's association.
- Initialize names before reading them and use meaningful names, clear scope and suitable types.
Official references#
- Python Language Reference — Assignment statements
- Python Language Reference — Data model
- Python Language Reference — Execution model
- Python Tutorial — An informal introduction to Python
- Python Standard Library — typing
- Python Standard Library — copy
Verification note: All eleven distinct runnable Python examples were executed in isolated namespaces on Python 3.13.5. Their outputs matched expectations. Three additional exception tests confirmed NameError for an undefined name, UnboundLocalError for premature local access, and NameError for an annotation-only module-level name. Official references are provided from established technical knowledge under the authorised offline research exception; live documentation and website rendering were not checked.
References
- 1.Python Language Reference — Assignment statementsdocs.python.org
- 2.Python Language Reference — Data modeldocs.python.org
- 3.Python Language Reference — Execution modeldocs.python.org
- 4.Python Tutorial — An informal introduction to Pythondocs.python.org
- 5.Python Standard Library — typingdocs.python.org
- 6.Python Standard Library — copydocs.python.org
Related questions
Explore other topics:Forward Deployed EngineeringMachine LearningSQL: Structured Query LanguageAI System Design