简体   繁体   中英

Python mutable/immutable containers

Are the following containers mutable or immutable in Python?

  • List

  • Tuple

  • Dictionary

List, Dictionary: Mutable

Tuple: Immutable

tuple - immutable

list- mutable

dictionary - mutable

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM