What are immutable objects?

15th Oct 2016, 9:44 AM
Kate Ml
Kate Ml - avatar
1 Answer
"Immutable" is an adjective that means "unchanging over time or unable to be changed". Therefore, immutable objects are objects whose state cannot be changed after it is created. They remain the same until they no longer exist (are deleted), e.g tuple. Mutable objects on the other hand can be changed, e.g list. Let's say we have a tuple and list as below a_tuple = (1,2,3); a_list = [1,2,3] We can change the first (or any other) element in the list just by reassigning its index: a_list[0] = 4 This will result in a_list = [4,2,3] But if we try to do same on the tuple: a_tuple[0] = 4 We will get a TypeError that says "'tuple' object does not support item assignment" Other examples of immutable (non-changeable) objects include Numeric types: int, float, complex; string; frozen set; bytes. Other examples of mutable (changeable) objects are dictionary, set, byte array. You can read more at https://codehabitude.com/2013/12/24/python-objects-mutable-vs-immutable/
15th Oct 2016, 11:25 AM
John Otu
John Otu - avatar