Python Variables: Memory Allocation, Object References & Dynamic Typing

In traditional languages such as C, C++, or Java, a variable is a strongly-typed memory container with a fixed size (e.g. int a = 10;). In Python, variables work fundamentally differently: variables are named tags (pointers) bound to objects residing in heap memory. Understanding this reference model is essential to mastering list mutability, function arguments, and memory optimization.

Python Variable Memory Model: Stack References to Heap Objects

Figure 6.1: Variables 'a' and 'b' pointing to the same int object (100) in heap memory via reference counting.


1. Creating and Assigning Variables in Python

You create a variable simply by assigning a value using the assignment operator (=). You never declare a type:

# Variable assignment in Python
age = 21                  # int object
price = 199.99            # float object
user_name = "Amit Kumar"  # str object
is_enrolled = True        # bool object

print(f"Name: {user_name}, Age: {age}, Price: ₹{price}")

2. Dynamic Typing & Type Re-Assignment

Because Python is dynamically typed, a variable can reference an integer at one moment and reference a string or list later in the same program:

x = 100
print(type(x))  # 

x = "Python Programming"
print(type(x))  # 

3. The id() Function & Object Identity

Every object created in Python receives a unique memory address. You can inspect this address using the built-in id() function, and compare object identities using the is operator:

# Python integer caching and object identity
x = 250
y = 250

print("id of x:", id(x))
print("id of y:", id(y))
print("x is y:", x is y)  # True (both point to the exact same cached object)

Important Note on CPython Integer Optimization: Python pre-allocates an internal array of integer objects for values between -5 and 256. When you create any integer within this range, Python reuses the existing cached object rather than creating a new one in memory.


4. Multiple and Chained Assignments

Python allows elegant multi-variable assignments in a single readable line:

# Chained assignment (same value to multiple variables)
a = b = c = 50
print(f"a={a}, b={b}, c={c}")

# Multiple assignment (tuple unpacking)
roll, course, marks = 101, "BCA", 94.5
print(f"Roll: {roll}, Course: {course}, Marks: {marks}")

# Swapping two variables without a temporary variable!
x, y = 10, 20
x, y = y, x
print(f"After swap: x={x}, y={y}")  # x=20, y=10

5. Type Casting (Type Conversion)

Type casting converts an object from one type to another using constructor functions:

• Implicit Conversion: Python automatically promotes smaller types to larger types (e.g. int + float -> float) to prevent data loss.

• Explicit Conversion: Using int(), float(), str(), list(), tuple(), set().

# Type conversion example
marks_str = "85"
marks_num = int(marks_str)  # Converts string "85" to integer 85
total = marks_num + 15
print("Total:", total)  # 100

Hands-on Practice Session

Challenge 1: Write a program to take two float inputs from the user, swap their values without using a third variable, and print their memory IDs before and after swapping.

# Solution:
num1 = 12.5
num2 = 45.8

print(f"Before Swap: num1={num1} (ID: {id(num1)}), num2={num2} (ID: {id(num2)})")
num1, num2 = num2, num1
print(f"After Swap:  num1={num1} (ID: {id(num1)}), num2={num2} (ID: {id(num2)})")

University Exam & Interview Questions

Q1 (BCA Exam Question): Differentiate between Mutable and Immutable objects in Python with examples.
Answer: Immutable objects cannot be modified in place after creation (e.g., int, float, str, tuple); any modification creates a brand new object in memory with a new ID. Mutable objects can be modified in place without altering their memory ID (e.g., list, dict, set).

Q2: What happens to unreferenced objects in Python?
Answer: When an object's reference count drops to zero, Python's automatic garbage collector immediately deallocates its memory.


Frequently Asked Questions (FAQ)

Can variable names start with a number in Python?

No. Variable names must begin with a letter (a-z, A-Z) or an underscore (_). They cannot start with a digit. See our Python Identifiers guide for complete naming rules.

Does Python have constant variables?

Python has no const keyword. By PEP 8 convention, variables written in ALL_CAPITAL_LETTERS (e.g., MAX_CONNECTIONS = 100) signal to developers that the value should not be modified.
Share Share on Facebook Share on Twitter Share on LinkedIn Pin on Pinterest Share on Stumbleupon Share on Tumblr Share on Reddit Share on Diggit

You may also like this!