Mutable and Imutable

It is safe to say that one can code Python without a thorough understanding of low-level programming. However, in order to master Python programming it is necessary to have certain degree of low-level programming knowledge. One reason is Python mutable and immutable objects. One way to divide Python data types into two subcategories is by their mutability. Mutable is a way of saying that an object can be changed (mutated) after its declaration.

Mutable Objects - are objects that can be changed. Some examples of mutable objects - list, dict, set.

Immutable Objects - are objects that can't be changed. Some examples of immutable objects - tuple, bool, int, float and str.

Object Type Mutable Immutable
List
dict
set
tuple
bool
int
float
str

As you can see in the example below, it is possible to change values of lists. However, trying to change the values of the tuples raises an error.

#Mutable and Immutable my_lst = [1, 2, 3, 4] my_tup = (1, 2, 3, 4) my_lst[0] = 5 my_tup[0] = 5

Python Memory Management

References

In Python variables point to the value. Actually they hold its address in memory - this is called a reference to the value. Lets look at an example:

When a string is assigned to a variable (x = "hey"), Python creates the string object ("hey") and finds free space in memory to store it. The variable x points to the address where the string is located. If another variable is assigned with the same string (y = "hey") the variable points to the same address in memory. The variables (x and y) are simply ways you can refer to the object. However, the data itself is still contained within the object in specific place of the computer memory. You can think about the variables as many names for the same person. Responsive image

If the x variable is changed and assigned with another object, it will point to another cell in the memory. When there are no more pointers left referencing to a specific object Python removes the object, thus freeing up the memory through a process called "garbage collection". Responsive image

Lists and Tuples

Lists and tuples can store the same objects. From a user standpoint, the only difference is that lists can be changed after their creation. At first one might think that there are no advantages of using tuples. However this is not the case!

1). Clean Code - As a programmer you want to minimize the risk for errors. If you store values in a specific order that is not supposed to change, it is best practice to use tuples. The use of tuples emphasizes that there is a reason for that specific sequence.

2). Efficacy - if there is no need for changing the sequence, the use of tuples is more efficient. Let's find out why!

Lists and Tuples Memory Management

Both tuples and lists hold references for the values they store (they don't store the values directly). When creating a tuple, Python finds place in memory that can store those pointers. However, when creating a list, Python finds more space than necessary in order make future changes possible.

Responsive image

The id() function

The id() function is a built-in function. It gets an object and returns its identity. This is guaranteed to be unique among simultaneously existing objects. Most of the cases it is the object's memory address.

#Mutable and Immutable my_num1 = 5 my_num2 = 5 print(id(my_num1) == id(my_num2)) my_str1 = 'pythontut' my_str2 = 'pythontut' print(id(my_str1) == id(my_str2)) my_list1 = [] my_list2 = [] print(id(my_list1) == id(my_list2)) my_tup1 = () my_tup2 = () print(id(my_tup1) == id(my_tup2))

Back to Lists and Tuples Memory Management

In the example above notice how empty tuples have the same id while empty lists have different id's. The reason is their mutability. Tuples aren't going to change. There is no reason to create the same object and to store it in memory if two tuples are exactly the same. It is much more efficient to point to the same place in memory. However, lists are supposed to change. If Python points to the same place in memory, we won't be able to change just one list. This is one more reason why tuples are more efficient than lists.

is vs ==

The is operator checks if two objects have the same id - meaning refer to the same object. The equality operator == compares the values of the objects. Hence two lists can retrun True for equality operator but Flase for 'is' operator.

Please notice - if two objects retrun True for 'is' operator, they must return True for equality operator.

#Mutable and Immutable list1 = [5] list2 = [5] print(list1 is list2) print(list1 == list2)

append() vs. + Operators on Lists

The append() method appends objects to the end of the list. It modifies the current list. When using the + operator, a new list is created and stored in memory along with the new objects. The process of copying the elements is not efficient, Therefore the append() method is much more efficient. However, there are cases when we would like to use the + operator. For instance, if we want to save a copy of the old list.