World's Best AI Learning Platform with profoundly Demanding Certification Programs
Designed by IITians, only for AI Learners.
Designed by IITians, only for AI Learners.
New to InsideAIML? Create an account
Employer? Create an account
Python objects are support both mutable and immutable property.
Immutable objects-
Those which do not let us modify their contents. Examples of these will be tuples, booleans, strings, integers, floats, and complexes.This means that after you create the object and assign some value to it, you can’t modify that value.
Simply the definition An immutable object is an object whose value cannot change.
Iterations on such objects are faster.
>>> tuple=(3,7,11) >>> tuple (3, 7, 11) >>> 2+4j (2+4j)
>>>str1 = "abcd" >>>str1[1] = 'x' --------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-61-c8ec484b923e> in <module> 2 str1 = "abcd" 3 ----> 4 str1[1] = 'x' TypeError: 'str' object does not support item assignment
Mutable objects –
Those that let you modify their contents. Examples of these are lists, sets, and dicts. Iterations on such objects are slower.
>>>list1 = [2,4,9] [2, 4, 9] >>>list1.append(10) >>>list1 [2, 4, 9, 10] >>>myset = {"apple", "banana", "cherry"} >>>myset.add("mango") >>>myset {'apple', 'banana', 'cherry', 'mango'} >>> dict1={1:1,2:2} >>> dict1[3]=3 >>> dict1 {1: 1, 2: 2, 3:3}
While two equal immutable objects’ reference variables share the same address, it is possible to create two mutable objects with the same content.