Reputation: 4706
Are the following containers mutable or immutable in Python?
List
Tuple
Dictionary
Upvotes: 1
Views: 2594
Reputation: 833
Mutable means value of a variable can be changed in the same memory block itself where the variable is stored or referenced.
Immutable means, when you try to change the value of a variable, it creates a new memory block and stores the new value over there.
Immutable -- Strings, Tuples, Numbers etc Mutable -- Lists, Dictionaries, Classes etc
Example:
Let us consider a List, which is mutable...
a=[1,2,3] suppose list 'a' is at a memory block named "A0XXX" now if you want to add 4,5 to the list... b=[4,5] append them both a +=b now a=[1,2,3,4,5] So, now final list 'a' is also stored at same memory block "A0XXX"
As list is mutable, it is stored at the same memory block.
If it is immutable, final list 'a' will be stored at the some other memory block "B0XXX" So mutable objects can be changed and stored at the same memory block, when you try to do the same with the immutable objects, a new memory block is created to store the changed values.
Upvotes: 6