8

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

jvperrin
3,3681 gold badge25 silver badges33 bronze badges
asked Jan 13, 2011 at 6:51

1 Answer 1

12

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
answered Jan 13, 2011 at 7:04
11
  • This checks whether it's a mutable sequence--not whether it's a mutable object. Dicts are clearly mutable objects, but isinstance({}, collections.MutableSequence) is false. Commented Jan 13, 2011 at 7:13
  • Yes, for dicts, MutableMapping is used. I didn't mention because I took the example of list. I will update it. Commented Jan 13, 2011 at 7:15
  • That doesn't work for sets. My point is just that collections won't tell you in a generic way whether an object is mutable or immutable. Commented Jan 13, 2011 at 7:27
  • Ok. Then what is the generic way to check for it? Feel free to update the answer. Commented Jan 13, 2011 at 7:29
  • @Sukbir: Add bytearray to the mutable chart (py3 only). Also there's array.array which may not be "built-in" in a narrow sense but is usually present. Commented Jan 13, 2011 at 7:52

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.