Internal Working of Python: Objects, References, Memory, and Copying
MY LEARNING JOURNEY · 07
Learning Python with Chai aur Code, one video at a time.
Learning source: Chai aur Code — Python Video 7
In this lesson, we went deeper into how Python works internally. We explored how variables refer to objects, how Python manages memory, what reference counts mean, and how copying works with mutable objects such as lists.
Some of these concepts initially sound complicated, but once we connect them to the examples, they become much easier to understand.
Let's break down what I learned.
1. Remember This: Types Belong to Objects, Not Variables
This is probably one of the most important things I took away from this lesson:
In Python, types belong to objects, not to variable names.
Let's understand that with an example:
number = 10
Here:
10is an integer object.numberis a name that refers to that object.- The object's type is
int.
We can verify this using:
type(number)
Output:
<class 'int'>
Now, let's assign a different value:
number = "Hello"
What happens?
The name number now refers to a string object instead of the integer object.
type(number)
Output:
<class 'str'>
Notice that we didn't declare number as an integer or a string.
Python determines the type from the object being referred to.
This is possible because Python is dynamically typed.
It means that we don't need to declare a variable's data type before assigning a value to it. The same name can be reassigned to objects of different types.
2. Is a Value an Object Only After a Variable Refers to It?
Initially, I imagined memory as a collection of small blocks, each storing a value.
I thought that when we wrote:
number = 10
The value 10 would first exist as some ordinary value in memory and become an object only when the variable number referred to it.
But that's not how Python's object model works.
The integer 10 is already an object. It doesn't need a variable name to become one.
For example:
print(type(10))
Output:
<class 'int'>
We can work with objects without assigning them to a variable first.
print("Hello".upper())
Here, "Hello" is a string object, even though we never assigned it a variable name.
Are Python objects the same as JavaScript objects?
No, and this is an important distinction.
In JavaScript, we often use objects with properties and key-value pairs:
let person = {
name: "Alex",
age: 20
};
Python also has objects with key-value pairs, such as dictionaries:
person = {
"name": "Alex",
"age": 20
}
However, Python's use of the word object is much broader.
An integer, string, list, function, and dictionary are all objects in Python.
So, when we say everything in Python is an object, we aren't saying that everything is a dictionary or a JavaScript-style object.
3. What Happens When an Object Is No Longer Referenced?
Let's say we write:
score = 5
Now, the name score refers to the integer object 5.
Imagine that we later remove the assignment:
del score
The name score is removed.
But what happens to the object 5?
If no other references to that object exist, it may become eligible for memory reclamation.
This brings us to garbage collection.
What Is Reference Counting?
In CPython, one of the main ways memory is managed is through reference counting.
A reference count tracks how many references an object has.
When an object's reference count reaches zero, CPython can generally reclaim its memory immediately.
For example:
a = [1, 2, 3]
b = a
Both a and b refer to the same list object.
Conceptually:
a ──────┐
├────► [1, 2, 3]
b ──────┘
Now:
del a
The name a is removed, but b still refers to the list.
Therefore, the list is still reachable and cannot be reclaimed just because a was deleted.
If we also execute:
del b
And there are no other references, the list can become eligible for reclamation.
CPython also has a cyclic garbage collector to handle certain reference cycles that reference counting alone cannot reclaim.
Does Python always delete unused objects immediately?
Not necessarily.
The exact memory-management behaviour depends on the Python implementation.
CPython also caches or interns certain objects to improve performance.
For example:
- Small integers are commonly cached.
- Some strings are interned.
True,False, andNoneare singleton objects.
This means that some objects may remain available for reuse even when a particular variable stops referring to them.
However, we shouldn't assume that Python keeps every unused integer or string in memory just in case it might be needed again.
4. Can We Check the Reference Count?
While learning about reference counting, I came across:
import sys
sys.getrefcount(parameter)
This function can give us the reference count of an object in CPython.
For example:
import sys
number = 10
print(sys.getrefcount(number))
But there's an interesting catch.
The number returned by sys.getrefcount() can be higher than we might expect.
Why does this happen?
The function call itself creates an additional temporary reference to the object being passed.
Other references may also exist because of Python's internal implementation.
So, the result isn't necessarily the number of variable names we've personally assigned to that object.
Also, reference-count behaviour is an implementation detail. Python doesn't provide one universally meaningful reference count across all implementations.
My takeaway: sys.getrefcount() is useful for experimenting with CPython's memory management, but we shouldn't treat its output as a perfect count of all the references we can see in our code.
5. What Happens When We Reassign an Integer?
Let's understand this with a familiar example:
a = 2
b = 5
a = a + 5
What happens internally?
Let's go step by step.
Step 1: Creating the initial references
a = 2
b = 5
The names refer to integer objects:
a ─────► 2
b ─────► 5
Step 2: Evaluating the right-hand side
Now we execute:
a = a + 5
Python evaluates the right-hand side first.
It looks up the object referred to by a, obtains its integer value 2, and evaluates:
2 + 5
The result is 7.
Step 3: Assigning the result
Since integers are immutable, Python doesn't modify the existing integer object 2 and turn it into 7.
Instead, the result is an integer object representing 7, and the name a is bound to that result.
Conceptually:
Before:
a ─────► 2
b ─────► 5
After:
a ─────► 7
b ─────► 5
The original object 2 is no longer referred to by a.
If nothing else refers to it, it may become eligible for reclamation. However, small integers such as 2 are commonly cached by CPython, so the object may remain available for reuse.
Does this happen only with integers?
No.
The same general idea applies to other immutable objects, such as strings and tuples.
For example:
name = "Python"
name = "JavaScript"
The original string isn't modified. The name is simply rebound to another string object.
Python also has singleton objects such as None, True, and False, which are reused rather than recreated as ordinary independent objects.
6. Can We Write a + 2 = a + 5?
No!
a + 2 = a + 5
This raises a SyntaxError.
Why?
Because the left side of an assignment must be something that Python can assign a value to, such as a variable name or an appropriate subscription.
For example:
a = a + 5
Here, a is a valid assignment target.
But a + 2 is an arithmetic expression. It produces a value; it isn't a variable name that can receive an assignment.
7. Understanding References With Lists
Now let's move from immutable objects to mutable objects.
Lists are particularly useful for understanding this difference.
Example 1: Reassigning a List
l1 = [1, 2, 3]
l2 = l1
l1 = [1, 2, 3]
l1[0] = 24
print(l1)
print(l2)
Output:
[24, 2, 3]
[1, 2, 3]
Why didn't changing l1 affect l2?
Let's understand the sequence.
Initially:
l1 = [1, 2, 3]
l2 = l1
Both names refer to the same list:
l1 ──────┐
├────► [1, 2, 3]
l2 ──────┘
But then we execute:
l1 = [1, 2, 3]
This creates a new list object and rebinds l1 to it.
Now:
l1 ─────────► [1, 2, 3]
l2 ─────────► [1, 2, 3]
These are two separate lists, even though their contents look identical.
So, when we modify:
l1[0] = 24
Only the new list referred to by l1 changes.
The list referred to by l2 remains untouched.
Example 2: Modifying a Shared List
Now let's remove the reassignment:
l1 = [1, 2, 3]
l2 = l1
l1[0] = 24
print(l1)
print(l2)
Output:
[24, 2, 3]
[24, 2, 3]
This time, both variables show the same modified list.
Why?
Because we never created a new list.
Both names still refer to the same mutable object:
l1 ──────┐
├────► [24, 2, 3]
l2 ──────┘
Since lists are mutable, we can modify their contents without creating a completely new list.
And because both names refer to that same object, both observe the change.
This is one of the most important differences between mutable and immutable objects.
8. What Is a Shallow Copy?
Now let's say we want to create a separate list instead of making two names refer to the same list.
We can use slicing:
l1 = [1, 2, 3]
l2 = l1[:]
l1[0] = 24
print(l1)
print(l2)
Output:
[24, 2, 3]
[1, 2, 3]
This works because:
l1[:]
Creates a shallow copy of the list.
A shallow copy creates a new outer list, but it doesn't recursively copy every object inside it.
For a simple list containing integers, this behaves as we might expect because the list structures are separate and integers are immutable.
Another way to create a shallow copy
Python provides a copy module.
import copy
l1 = [1, 2, 3]
l2 = copy.copy(l1)
Here, copy.copy() creates a shallow copy.
But what if a list contains another list?
This is where shallow copying gets interesting.
Consider:
l1 = [[1, 2], [3, 4]]
l2 = l1[:]
l1[0][0] = 99
print(l1)
print(l2)
Output:
[[99, 2], [3, 4]]
[[99, 2], [3, 4]]
Why did both lists change?
Because the outer lists are separate, but their inner lists are still shared.
Conceptually:
l1 ─────► Outer list A ─────┐
├────► [1, 2]
l2 ─────► Outer list B ─────┘
l1 and l2 also share the inner list [3, 4]
When we modify an element inside one of those shared inner lists, both outer lists show the change.
So, a shallow copy doesn't recursively copy nested objects.
9. What Is a Deep Copy?
To overcome the shared nested-object behaviour of shallow copying, Python provides deep copying.
We can use:
import copy
l1 = [[1, 2], [3, 4]]
l2 = copy.deepcopy(l1)
l1[0][0] = 99
print(l1)
print(l2)
Output:
[[99, 2], [3, 4]]
[[1, 2], [3, 4]]
Why?
Because copy.deepcopy() recursively copies nested objects instead of simply copying the outer list.
Now, the inner lists are also separate.
Conceptually:
l1 ─────► [[1, 2], [3, 4]]
l2 ─────► [[1, 2], [3, 4]]
Although their contents initially look the same, their nested list objects are separate.
Shallow Copy vs Deep Copy
| Feature | Shallow copy | Deep copy |
|---|---|---|
| Creates a new outer object | Yes | Yes |
| Copies nested objects recursively | No | Yes |
| Shares nested mutable objects | Usually yes | Generally no |
| Python method | copy.copy() |
copy.deepcopy() |
One thing to remember: deep copying has some special cases and limitations, particularly with objects such as files, sockets, and other resources. It is not always appropriate to deep-copy every object.
10. Difference Between == and is
This is another important distinction.
Let's say we create two lists:
m = [1, 2, 3]
n = [1, 2, 3]
Now:
m == n
Output:
True
Why?
Because == checks whether the values are equal.
Both lists contain the same elements in the same order.
But what about:
m is n
Output:
False
Why?
Because is checks whether both names refer to the exact same object.
Here, we created two separate lists.
Let's compare that with another example:
m = [1, 2, 3]
n = m
Now:
m == n
Output:
True
And:
m is n
Output:
True
This time, both names refer to the same list object.
Quick Comparison
| Operator | What it checks |
|---|---|
== |
Whether two objects have equal values |
is |
Whether two references point to the same object |
A useful Python convention is to use is when checking for singleton values such as None:
if value is None:
print("No value")
For ordinary value comparisons, use ==.
11. My Key Takeaways
Here's what I understood from this lesson:
- Types belong to objects, not variable names. A variable name can refer to objects of different types at different times.
- Everything in Python is an object in the broad sense, including integers, strings, lists, functions, and dictionaries.
- Reference counting is an important part of memory management in CPython.
- Objects whose reference counts reach zero can generally be reclaimed by CPython.
- Small integers and certain other objects may be cached or reused by Python implementations.
- Reassigning an immutable object doesn't modify the original object.
- Two variables can refer to the same mutable object, so modifying that object can be visible through both names.
- Shallow copying creates a new outer object but can leave nested objects shared.
- Deep copying recursively copies nested objects.
==checks value equality, whereasischecks object identity.
Final Thoughts
This lesson helped me connect many of the concepts we had discussed in previous videos.
Earlier, I understood that variables refer to objects, but I didn't fully understand how that affects memory management and copying.
The list examples were particularly useful because they showed why assigning one list to another variable isn't the same as creating a copy.
I also found the difference between shallow and deep copying interesting. At first, I thought copying a list would automatically create completely separate copies of everything inside it. Now I understand why nested lists can behave differently.
One of my biggest takeaways is that understanding references is essential to understanding how Python handles mutable and immutable objects.
And the difference between == and is is another small detail that can prevent some confusing bugs later on.
This is part of my Python learning journey, where I document what I understand from each Chai aur Code lecture, the questions I encounter, and the concepts I explore along the way.
Did I misunderstand anything about Python's internal working, reference counting, or copying? If you have a simpler explanation or a useful example, I'd love to learn from you in the comments.
About the author
- As a newbie, learning Python, bit by bit and error by error. I write about the things I learn, the queries I have and things I finally understand. If you’re learning as well, let’s do this together!
Comments
Join the discussionNo comments yet. Be the first to comment.
Python Learning Journey
I'm documenting my journey of learning Python through Chai aur Code, one video at a time. I'll share what I understand, the questions I encounter, the concepts I explore with AI, and the code I experiment with along the way. My goal is to learn by questioning, explaining concepts in my own words, and sharing the journey publicly. I'm a beginner, and I'm always open to suggestions that can help me learn better.

