Python Objects: Mutable vs Immutable

Python Objects: Mutable vs Immutable

If you have started learning python, you will have noticed that changing a list in python affects all its references, but modifying a string creates a new one, right? In this post, we will talk about how python manages memory, and handles function arguments.

ID and Type

before we talk about mutability, let's start with explaining the two fundamental concepts, id() and type(). The id function returns a unique identifier for an object, while the type function returns the type of the object.

x = 5
print(id(x))   # Unique id for the integer object 5
print(type(x)) # <class 'int'>
        

Mutable and Immutable Objects

These objects are those that can be changed after creation, while immutable objects are those that cannot be changed. Mutable objects include: Lists, dictionaries, sets, and Byte arrays. Immutable objects include: strings, Tuples, Numbers (int, float, complex), and Bytes.

For example:

my_list = [1, 2, 3]
print(id(my_list))  # Output: 140721154997808
my_list.append(4)
print(my_list)  # Output: [1, 2, 3, 4]
print(id(my_list))  # Output: 140721154997808        

Notice how id remains the same after modification? this is mutability.

my_string = "Hello"
print(id(my_string))  # Output: 140721154997808
my_string += " World"
print(my_string)  # Output: Hello World
print(id(my_string))  # Output: 140721155001904        

In this case when a new string is created, the id changes. This is immutability.

Immutable vs Mutable

Now we've learnt that some things change and others don't. in those that don't change we have numbers. If you're dealing with numbers in the common range (between -5 and 256 if you're using Cpython), python uses the same spot in memory for them over and over. But for others that can change, Python needs to be ready for what you might do with it so it sets up space for these changes as they come along, which means you have a lot of flexibility. If you change the items that can change, they get rewritten right where they are. But for those that cannot change, it makes new versions every time there is a change.

Tackling Function Arguments

In python, when you pass an argument into functions you're giving them assignments, i.e: touch a mutable item in a function and you'll change the outside of the function too. But id that item is not mutable, every modification inside the function ends up making something brand new, leaving the original unchanged.

For example,

def modify_list(lst):
    lst.append(4)  # Modifies the list in-place

def modify_string(s):
    s += " World"  # Creates a new string object

my_list = [1, 2, 3]
modify_list(my_list)
print(my_list)  # [1, 2, 3, 4] - yeah the list got changed

my_string = "Hello"
modify_string(my_string)
print(my_string)  # "Hello" - still the same        

So yes, understanding the differences between changeable and unchangeable items (mutable and immutable objects), in python helps use to save memory, create better functions, and understand the side effects when handling large data structures.


To view or add a comment, sign in

Insights from the community

Others also viewed

Explore topics