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 )
my_str='plus2net.com'
print(my_str[4])
my_str[4]='5'
Above code will generate error saying TypeError: 'str' object does not support item assignment

Using List ( mutable )
my_list=[1,2,3]
my_list[1]=8
print(my_list) # [1, 8, 3]
Using a tuple ( immutable )
my_tuple=(1,2,3)
my_tuple[1]=8
print(my_tuple)
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.
my_list=[1,2,3]
str1='welcome'
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.
my_list[1]=7 
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
str1='Python' 
print("address of string str1 : ", id(str1))
Output
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


Subscribe

* indicates required
Subscribe to plus2net

    plus2net.com



    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-2024 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer