-3

I am feeling very strange when I am working on list, dictionary and tuple in python.

When we declare multiple variable in one line like a = b = c = 0 it behaves like separate variables.

If we are update value any of the above variables then it will not affect another variable like below.

a = 10
b = 11
c = 13

But, this thing is not applying with list, tuple and dictionary. If we declare blank list like below.

a = b = c = []

Now, I am appending a value to only a list.

a.append('Testing')

Now, b and c are automatically assigned that value.

This thing also happens with dictionary and tuple also.

I have to know that why it is not accept to declare it like above example.

wjandrea
  • 28,235
  • 9
  • 60
  • 81
Mayur Jotaniya
  • 304
  • 1
  • 18

1 Answers1

1

This is a concept of mutable and immutable objects. When you write a code like a = b = c = [], all the variables are referencing the same object. If this object is mutable, when you change the object from any of the variables, the other two variables will reflect the change too. Some object types are mutable, others not.

You can read the article bellow to have a more complete answer.

https://medium.com/@meghamohan/mutable-and-immutable-side-of-python-c2145cf72747

chepner
  • 497,756
  • 71
  • 530
  • 681