Python: Mutable and Immutable Objects

In Python, an object is data of a single data type and objects are referred to with variables.

type() is a function that returns the data type of an object.

id() returns an integer associated with the object that is unique and does not change. It can be thought of as the address of the object in memory.

Using these two functions, we can check to see how different types of objects are associated with variables and how objects can be changed (or not changed).

Mutable Objects

Mutable objects are objects that can be changed. Lists, sets, and dicts are mutable. When you change the value of an object, all variables associated with that object refer to the new data.

Immutable Objects

Immutable objects cannot be changed. Strings, numbers (int, float, etc.), and tuples are immutable. Attempting to change immutable objects or trying to use methods that would change an object will result in an error.

However, the variables associated with an object can be reassigned, effectively “changing” their values, whether the object is mutable or not. So while immutable objects can’t be changed in place, they can be “changed” by creating a copy of that object with the new changes and reassigning the variable to the new, changed copy.

This is important to know when storing and changing data of different types in Python. For example, you might want to change the value of a but keep the value of b, so what methods you use to change the value will depend on what type the object is.

Passing Objects into Functions

When a mutable object is passed into a function, the function can directly change the object’s contents.

When an immutable object is passed into a function, the object’s contents cannot be changed but the variable pointing to that object can be changed.

Knowing the difference between mutable and immutable types and how they are treated when passed into functions can make a big difference in code and memory efficiency. For example, with a mutable type such as list, using + to add elements works just fine. However, concatenating multiple strings (an immutable type) using + would require making several copies of the string over and over again. Instead, it’s better to use the .join() method to get rid of the need to make multiple string copies and therefore be more efficient.

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.