Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (50.2k points)

I want to know about immutable type as I am very much confused about that topic. I understand the floating object is considered to be immutable, with this kind of example from my book:

class RoundFloat(float):

    def __new__(cls, val):

        return float.__new__(cls, round(val, 2))

Is this considered to be immutable because of the class structure/hierarchy? 

class SortedKeyDict(dict):

    def __new__(cls, val):

        return dict.__new__(cls, val.clear())

Whereas something mutable has functions inside the class, with this type of example:

class SortedKeyDict_a(dict):

    def example(self):

        return self.keys()

Also, for the last class(SortedKeyDict_a), if I pass this type of set to it:

d = (('zheng-cai', 67), ('hui-jun', 68),('xin-yi', 2))

without referring to the example function, it returns a dictionary. 

1 Answer

0 votes
by (107k points)

Kindly be informed that float data types are mutable data:

x = 5.0

x += 7.0

print x # 12.0

On the other hand, strings are immutable. But you can do the same thing.

s = 'foo'

s += 'bar'

print s # foobar

The literals are changing, but it changes by changing what the variable refers to. A mutable type can get changed in that way, and it can also change "in place".

Here is the difference:

x = something # immutable type

print x

func(x)

print x # prints the same thing

x = something # mutable type

print x

func(x)

print x # might print something different

x = something # immutable type

y = x

print x

# some statement that operates on y

print x # prints the same thing

x = something # mutable type

y = x

print x

# some statement that operates on y

print x # might print something different

Concrete examples:

x = 'foo'

y = x

print x # foo

y += 'bar'

print x # foo

x = [1, 2, 3]

y = x

print x # [1, 2, 3]

y += [3, 2, 1]

print x # [1, 2, 3, 3, 2, 1]

def func(val):

    val += 'bar'

x = 'foo'

print x # foo

func(x)

print x # foo

def func(val):

    val += [3, 2, 1]

x = [1, 2, 3]

print x # [1, 2, 3]

func(x)

print x # [1, 2, 3, 3, 2, 1]

Want to learn more concepts related to Python? Join this Python online Course by Intellipaat. 

Related questions

0 votes
1 answer
0 votes
1 answer
asked May 30, 2020 in Python by Sudhir_1997 (55.6k points)
0 votes
1 answer
asked Feb 23, 2021 in Java by Jake (7k points)
0 votes
2 answers
asked Feb 18, 2021 in Java by Harsh (1.5k points)
0 votes
1 answer
asked Jun 17, 2020 in Python by Sudhir_1997 (55.6k points)

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...