Python Variables
Introduction to Variables
Variables in Python are names that reference objects stored in memory. They are created when you first assign a value and can point to different types over their lifetime.
Key characteristics:
- Created automatically upon assignment
- No type declaration needed
- Act as references to objects in memory
- Support dynamic typing (type inferred at runtime)
Variable Assignment
Example
# Basic variable assignment
x = 5 # Integer
y = "Hello" # String
z = 3.14 # Float
is_valid = True # Boolean
# Multiple assignment
a, b, c = 1, 2, 3 # a=1, b=2, c=3
# Same value assignment
p = q = r = 42 # All point to the same integer object
ℹ️ Note: Variables store references, not actual values. Assignment makes a name point to an object.
Variable Types in Memory
⚠️ Warning: Python may reuse memory for immutable values (like small integers and short strings). Use `id()` to check an object’s identity.
Variable | Type | Value |
---|---|---|
x | int | 5 |
y | str | 'Hello' |
z | float | 3.14 |
is_valid | bool | True |
Advanced Variable Concepts
Because variables are references, assigning one variable to another does not create a copy—it creates a new reference to the same object.
Example
# References and identity
original = [1, 2, 3]
reference = original # Both refer to same list
reference[0] = 99 # Changes also affect 'original'
print(original) # [99, 2, 3]
print(original is reference) # True
# To copy, create a new object
from copy import deepcopy
new_copy = deepcopy(original)
print(original is new_copy) # False
Output
[99, 2, 3] True False
ℹ️ Note: Use `is` to check if two variables point to the same object.