 # Week 5, exercise of list

Sir,
This is the solution of list exercise
And I understand that we have to make a deep copy of our list if we want to change of our main list doesn’t effect on copied list
But, when I use that formula on a integer it seems that change in b doesn’t effect on a
See the attachment below -
Thank you.
Nayan Das

1 Like

True, that’s because

• int, float, decimal, bool, string, tuple, and range are immutable datatypes.
• list, dictionary, set and user-defined classes are mutable datatypes.

What does that mean?
See example below:

``````a = 10
b = a
print("id of a : ", id(a))
print("id of b : ", id(b))
for i in range(3):
b = b * 10
print("iteration ", i+1)
print("a = ", a, "and id of a : ", id(a))
print("b = ", b, "and id of b : ", id(b))
``````

and its output :

``````id of a :  10914784
id of b :  10914784
iteration  1
a =  10 and id of a :  10914784
b =  100 and id of b :  10917664
iteration  2
a =  10 and id of a :  10914784
b =  1000 and id of b :  140349804277488
iteration  3
a =  10 and id of a :  10914784
b =  10000 and id of b :  140349804275824
``````

Notice that - id of `b` changes each time a value is assigned to `b` (except at the time of initialization).

Now take a look at the same example for list:

``````list_a = 
list_b = list_a
print("id of list_a: ", id(list_a))
print("id of list_b: ", id(list_b))
for i in range(1,4):
list_b.append(list_b[i-1]*10)
print ("iteration ", i)
print("list_a = ", list_a, "and id of list_a: ", id(list_a))
print("list_b = ", list_b, "and id of list_b: ", id(list_b))
``````

and its output is:

``````id of list_a:  140349794556424
id of list_b:  140349794556424
iteration  1
list_a =  [10, 100] and id of list_a:  140349794556424
list_b =  [10, 100] and id of list_b:  140349794556424
iteration  2
list_a =  [10, 100, 1000] and id of list_a:  140349794556424
list_b =  [10, 100, 1000] and id of list_b:  140349794556424
iteration  3
list_a =  [10, 100, 1000, 10000] and id of list_a:  140349794556424
list_b =  [10, 100, 1000, 10000] and id of list_b:  140349794556424
``````

Notice that id of `list_a` and `list_b` are the same at all times.
This is why, you need to do deep copy in case of lists, if you really want 2 different copies.

Hence, point to remember is :

• int, float, decimal, bool, string, tuple, and range are immutable datatypes.
• list, dictionary, set and user-defined classes are mutable datatypes.
3 Likes