All Courses

Objects in Python are mutable or immutable?

By Rama, 2 years ago
  • Bookmark

Can we change python object ?

1 Answer

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

>>>str1 = "abcd"

>>>str1[1] = 'x'
TypeError                                 Traceback (most recent call last)
<ipython-input-61-c8ec484b923e> in <module>
      2 str1 = "abcd"
----> 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]


[2, 4, 9, 10]

>>>myset = {"apple", "banana", "cherry"}


{'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.

Your Answer


Live Masterclass on : "How Machine Get Trained in Machine Learning?"

Jun 1st (5:32 PM) 515 Registered
More webinars

Related Discussions

Running random forest algorithm with one variable

View More