Wednesday, April 24, 2024

📑 Mutable and Immutable Types

📑 Task

1) What will the program print?
2) Is it possible to create a dictionary of objects of another type:
during manipulations with variables or copies
they will behave differently and will not repeat changes of each other?
What type of objects should they be?
x1 = [[]]
x2 = x1
x1 *= 2
d1 = {1: x1}
d2 = {1: x2}
print(x1, x2)
print(d1, d2)
x1[0].append(2)
print(x1, x2)
print(d1, d2)
d2[1] += [[3]]
print(x1, x2)
print(d1, d2)

📑 Answer

1) Changes to copies and originals will affect each other
[[], []] [[], []]
{1: [[], []]} {1: [[], []]}
[[2], [2]] [[2], [2]]
{1: [[2], [2]]} {1: [[2], [2]]}
[[2], [2], [3]] [[2], [2], [3]]
{1: [[2], [2], [3]]} {1: [[2], [2], [3]]}
2) The object type must be immutable, for example integers
x1 = 1
x2 = x1
x1 *= 2
d1 = {1: x1}
d2 = {1: x2}
print(x1, x2)
print(d1, d2)
x1 += 2
print(x1, x2)
print(d1, d2)
d2[1] += 3
print(x1, x2)
print(d1, d2)

No comments:

Post a Comment