Objects in Python are mutable or immutable?

By Rama, 3 months ago
  • Bookmark
0

Can we change python object ?

Object
Mutable
Immutable
1 Answer
0

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.


Your Answer

Webinars

More webinars

Related Discussions

Running random forest algorithm with one variable

View More
BOT
Agent(Online)
We're Online!

Chat now for any query