Internal Working of Python

Part 1: Mutable and Immutable Objects

Hello, fellow learners and programmers! Welcome to my first article, where I'll delve into the fundamental concepts of Python's internal workings. Today, we'll explore the distinction between mutable and immutable objects in Python and understand how they impact the way Python operates under the hood.

Mutable Objects: Mutable objects in Python can be modified or changed after their creation, directly affecting the object in memory.

Example:

my_list = [1, 2, 3]
my_list[0] = 100
print(my_list)  # Output: [100, 2, 3]

Immutable Objects: On the other hand, immutable objects in Python cannot be modified once created. Operations that seem to modify immutable objects actually create new objects.

Example:

my_string = "Hello"
my_string = my_string + ", World!"
print(my_string)  # Output: Hello, World!

While this distinction might be familiar to many, let's dive a bit deeper into these concepts.

Suppose we create variables v1 and v2:

v1 = 5
v2 = v1  # Assigning the value of v1 to v2

Now, if we print the values of v1 and v2, we get:

print(v1)  # Output: 5
print(v2)  # Output: 5

If we change the value of v1 and reassign another value, what happens to v2?

v1 = 10
print(v1)  # Output: 10
print(v2)  # Output: 5

Surprisingly, the value of v2 remains unchanged. But why? In this article, we'll explore the intricacies of value assignment and memory workings in Python.

Thank you for reading this first part! While these concepts might be familiar to many, they lay the groundwork for our deeper exploration in the upcoming parts of this series. Stay tuned for more!