In Python, variables are not memory containers with fixed types (like in C or Java). Instead, variables are names (labels/pointers) that reference objects stored in memory.
Python Variables, Dynamic Typing & Naming Rules
In-depth exploration of Python variables as object references, dynamic typing, multiple assignments, id() memory inspection, naming rules, and keywords.
1Variables in Python: Names Bound to Objects
2Dynamic Typing in Action
A variable can reference an integer at one moment, and later reference a string or list without causing compile errors:
data = 42 # data points to an integer object
data = "Now text" # data now points to a string object3Python Naming Rules (Identifiers)
- Must start with a letter (
a-z,A-Z) or an underscore (_). - Cannot start with a digit (e.g.,
2useris invalid, butuser2is valid). - Can only contain alphanumeric characters and underscores (
a-z, A-Z, 0-9, _). - Case-sensitive (
age,Age, andAGEare three distinct variables). - Cannot be a Python reserved keyword (such as
if, for, class, def, return, while, import).
4Memory Address Inspection with id()
a = [1, 2, 3]
b = a # b points to the SAME list in memory (id(a) == id(b))
c = [1, 2, 3] # c is a NEW list with identical contents (id(a) != id(c))
π» Complete Executable Code Example
Python 3
βΆ Run in Compiler
import keyword
# Multiple assignment in Python
name, age, is_student = "Alex", 24, True
print(f"π€ Name: {name}, Age: {age}, Student: {is_student}")
# Swapping variables without a temp variable
x, y = 10, 20
print(f"Before swap: x = {x}, y = {y}")
x, y = y, x
print(f"After swap: x = {x}, y = {y}")
# Check memory identity
num1 = 500
num2 = num1
print(f"Memory id of num1: {id(num1)}, num2: {id(num2)} (Same: {id(num1) == id(num2)})")
# Display Python's 35 Reserved Keywords
print(f"
π Total Reserved Keywords in Python 3: {len(keyword.kwlist)}")
print(", ".join(keyword.kwlist[:12]), "...")
β οΈ Common Pitfall: Naming Variables After Built-in Functions
Avoid naming variables list, str, int, dict, or sum. Doing so shadows Pythonβs built-in functions and causes unexpected errors later in your script.
π» Try It Yourself β Hands-on Practice Challenge
Observe how mutable lists vs immutable numbers behave during reassignment.
Python 3
βΆ Run in Compiler
list_a = [10, 20, 30]
list_b = list_a
list_b.append(40)
print("list_a:", list_a)
print("list_b:", list_b)
print("Are they identical objects?", list_a is list_b)
β Frequently Asked Questions (FAQ)
Q: What is snake_case vs camelCase?
PEP 8 recommends snake_case (lowercase with underscores: total_price, user_id) for Python variables and functions, whereas CamelCase (UserProfile) is used for classes.