mutable and immutable objects

Objects in Python can be Mutable or immutable.
Identities remain same for mutable objects but changes for immutable objects.

Mutable and immutable object and id()

For mutable objects by changing the element the id() value will not change , whereas for immutable objects id() value will change.
List is a mutable object but tuple is a immutable object.

Check how the identities of list and tuple are changing after adding elements.

Immutable objects are tuple, string, int
mutable objects are list, dictionary , set

Let us try one string ( immutable )
Above code will generate error saying TypeError: 'str' object does not support item assignment

Using List ( mutable )
print(my_list) # [1, 8, 3]
Using a tuple ( immutable )
Above code will generate error saying TypeError: 'tuple' object does not support item assignment

Comparing list( Mutable ) with string ( immutable )

When we assign a different value to a string variable we are not modifying the string object, we are creating a new string object.
But when we change any element of a list we are not creating a different object, we are only modifying the same object.
print("address of list : ", id(my_list))
print("address of string str1 : ",id(str1))

# change the values 
# modified the list object, not a new object , address is same.
print("address of list : ", id(my_list))

# str1[1]='p' # this will generate error 
# new string object is created now, 
# not modified the old one, address changed
print("address of string str1 : ", id(str1))
address of list :  140301581527624
address of string str1 :  140301582741432
address of list :  140301581527624
address of string str1 :  140302155689016
Address of the string is changed when we assign a different value to it, as string is immutable
Address of list remain same as we add or update elements of it, as string is mutable.
We can make elements of an iterator immutable or unchangeable by using frozenset()
hash() : Hashable and Immutable objects id()
any() Iterator in and not in: The Membership operators

Subscribe to our YouTube Channel here


* indicates required
Subscribe to plus2net

    Post your comments , suggestion , error , requirements etc here

    Python Video Tutorials
    Python SQLite Video Tutorials
    Python MySQL Video Tutorials
    Python Tkinter Video Tutorials
    We use cookies to improve your browsing experience. . Learn more
    HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
    ©2000-2023 All rights reserved worldwide Privacy Policy Disclaimer