Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chart of mutable versus immutable types

Is there a table or a chart somewhere online which shows what types (inbuilt) are mutable and immutable in python?

like image 753
pandoragami Avatar asked Jan 13 '11 06:01

pandoragami


People also ask

How do you know if its mutable or immutable?

An object is mutable if it is not immutable. An object is immutable if it consists, recursively, of only immutable-typed sub-objects. Thus, a tuple of lists is mutable; you cannot replace the elements of the tuple, but you can modify them through the list interface, changing the overall data. Save this answer.


1 Answers

I am not sure of a chart, but basically:

Mutable:

list, dictionary, bytearray Note: bytearray is not a sequence though.

Immutable:

tuple, str

You can check for mutability with:

>>> import collections
>>> l = range(10)
>>> s = "Hello World"
>>> isinstance(l, collections.MutableSequence)
True
>>> isinstance(s, collections.MutableSequence)
False

For a dictionary (mapping):

>>> isinstance({}, collections.MutableMapping)
True
like image 184
user225312 Avatar answered Sep 28 '22 01:09

user225312