In Python, variables are symbolic names bound to objects in memory.
Dynamic Typing & Object References: Unlike statically typed languages where variables represent fixed memory locations, Python variables act as pointers to objects. Inspect an object's type with type(), verify its memory address using id(), or convert types with int(), float(), and str(). For naming constraints, consult reserved keywords and learn namespace isolation in variable scope.
| C / C++ Model | Python Reference Model |
|---|---|
Fixed Container: Variable is a fixed RAM slot of a single type.int x = 5; → [Memory Slot 0x100: Value 5]
|
Name Tag / Pointer: Variable is a pointer to an object on the heap.x = 5 → Variable x points to PyObject_Int(value=5)
|
| Reassignment overwrites memory bytes directly. | Reassignment moves the pointer to a new object. |
Every variable name in Python is an identifier. Identifiers must follow standard syntactic rules:
a-z, A-Z, digits 0-9) and the underscore (_).4t = 56 triggers a SyntaxError).$, @, #, %, and hyphens (-) are invalid.student_age, Student_Age, and STUDENT_AGE are three distinct variables.for, class, def, or global as variable names (see reserved keywords).str.isidentifier().Variables are initialized automatically the moment they are assigned a value using the assignment operator (=):
# 1. Variable Declaration and Multiple Assignment
a = 45
my_name = "Raju"
_mark = 65
address = "World"
print("Values:", address, my_name, _mark, a)
# Multiple assignment in a single statement
width, height = 710, 710
x1, y1, x2, y2 = 5, 5, width - 5, height - 5
print(f"Dimensions: {width}x{height}, Box: ({x1}, {y1}) to ({x2}, {y2})")Terminal Output:
Values: World Raju 65 45
Dimensions: 710x710, Box: (5, 5) to (705, 705)
Python is dynamically typed. A variable does not have a permanently locked type; rather, it takes on the type of whatever object it currently references:
# 2. Dynamic Typing and Type Reassignment
val = "plus2net"
print("Initial type:", type(val), "-> Value:", val)
# Reassigning the same variable name to an integer
val = 420
print("Updated type:", type(val), "-> Value:", val)Terminal Output:
Initial type: <class 'str'> -> Value: plus2net
Updated type: <class 'int'> -> Value: 420
When you assign one variable to another (y = x), you create an alias pointing to the exact same object in memory. You can inspect the unique memory address using id():
# 3. Python Object Pointer Model: Name Tags vs. Memory Objects
x = [1, 2, 3]
y = x # y references the exact same object in heap memory
print("id(x) == id(y):", id(x) == id(y))
print("x is y: ", x is y)
y.append(4)
print("x after y.append():", x)Terminal Output:
id(x) == id(y): True
x is y: True
x after y.append(): [1, 2, 3, 4]
Python prevents implicit operations between incompatible types (such as adding an integer to a string). You must convert types explicitly using constructor functions:
# 4. Explicit Type Conversions Between Data Types
a = "45" # String representation
b = 42 # Integer literal
# Adding a string and integer directly raises TypeError:
# print(a + b) # TypeError: can only concatenate str to str
print("Concatenation as text: ", a + str(b))
print("Mathematical addition: ", int(a) + b)Terminal Output:
Concatenation as text: 4542
Mathematical addition: 87
Python allows unpacking iterables (such as lists or tuples) directly into variables, as well as swapping variables without temporary variables:
# 5. Variable Packing and Extended Unpacking (* operator)
# Swapping variables without temporary storage
x, y = 5, 10
x, y = y, x
print(f"Swapped: x={x}, y={y}")
# Extended sequence unpacking
user_data = "plus2net"
first, second, *rest = user_data
print("First: ", first)
print("Second:", second)
print("Rest: ", rest)Terminal Output:
Swapped: x=10, y=5
First: p
Second: l
Rest: ['u', 's', '2', 'n', 'e', 't']
Variables declared inside a function have local scope and are destroyed when the function exits. Variables declared at the script level have global scope:
global var_name.Use the del statement to remove a variable name from the namespace. Subsequent access raises a NameError, which can be handled using try...except error handling:
# 6. Deleting Variables with del & NameError Handling
counter = 100
print("Counter exists:", counter)
del counter
try:
print(counter)
except NameError as err:
print("Caught expected exception:", err)Terminal Output:
Counter exists: 100
Caught expected exception: name 'counter' is not defined
Python has no keyword for immutable constants. Instead, PEP 8 defines a naming convention using all-uppercase letters with underscores to indicate values that should remain unchanged:
# 7. Constant Conventions in Python (UPPER_CASE naming)
# Python does not enforce immutable constants at the syntax level;
# by PEP 8 convention, constants are written in uppercase.
PI = 3.14159
MAX_CONNECTIONS = 500
BASE_URL = "https://www.plus2net.com"
print("API Endpoint:", f"{BASE_URL}/api/v1")
print("Max limit: ", MAX_CONNECTIONS)Terminal Output:
API Endpoint: https://www.plus2net.com/api/v1
Max limit: 500
Practice variable assignment, object pointer inspections, type conversions, and scope rules in our interactive companion Jupyter Notebook:
Explore interactive code cells, verify memory IDs with id(), practice sequence unpacking, and run self-validating assertions.
Run these unit checks directly in Python or your local environment to verify variable mechanics:
# 8. Self-verifying unit test suite for variable operations
# Test 1: Multiple assignment
a, b = 10, 20
assert a == 10 and b == 20
# Test 2: In-place value swap
a, b = b, a
assert a == 20 and b == 10
# Test 3: Type conversion
s = "100"
assert int(s) == 100
assert str(50) == "50"
# Test 4: Extended unpacking
h, *tail = [1, 2, 3, 4]
assert h == 1 and tail == [2, 3, 4]
# Test 5: Deletion raising NameError
tmp = 999
del tmp
try:
_ = tmp
assert False, "NameError not raised"
except NameError:
pass
print("All variable unit assertions successfully verified!")Terminal Output:
All variable unit assertions successfully verified!
No. Python is dynamically typed; variables are created automatically upon assignment and infer their data type from the assigned value.
No. Variable names must start with an alphabetic letter (a-z, A-Z) or an underscore (_). Starting with a digit causes a SyntaxError.
Use tuple unpacking: x, y = y, x. Python evaluates the right-hand side first, swapping values without a temporary variable.
Python does not have built-in constants. The convention is to use uppercase variable names (e.g., MAX_LIMIT = 100) to signal they should not be modified.
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.