Python3: Mutable, Immutable… everything is object!
Objects have individuality and multiple names, they can be linked to the same object, this is known as aliasing in other languages, this is not apparent at first sight in python and it can be easily ignored when dealing with basic and immutable data types such as numbers , strings or tuples. However aliasing has a surprising effect on Python code semantics involving mutable objects such as lists, dictionaries, and other types. This works to the benefit of the program, as the names work as pointers in some respects. For example, passing an object is simple since only the pointer is passed, and if a function modifies the object that was passed, the caller will see the change, this eliminates the need to have 2 different ways of passing arguments
Función Python id ()
id() function returns a unique id for the specified object.
All objects in Python has its own unique id.
The id is assigned to the object when it is created.
The id is the object’s memory address, and will be different for each time you run the program. (except for some object that has a constant unique id, like integers from -5 to 256)
The type() function either returns the type of the object or returns a new type object based on the arguments passed.
Every variable in python holds an instance of an object. There are two types of objects in python i.e. Mutable and Immutable objects. Whenever an object is instantiated, it is assigned a unique object id. The type of the object is defined at the runtime and it can’t be changed afterwards. However, it’s state can be changed if it is a mutable object.
To summarise the difference, mutable objects can change their state or contents and immutable objects can’t change their state or content.
Immutable Objects : These are of in-built types like int, float, bool, string, unicode, tuple. In simple words, an immutable object can’t be changed after it is created.
Mutable Objects : These are of type list, dict, set . Custom classes are generally mutable.
- Mutable and immutable objects are handled differently in python. Immutable objects are quicker to access and are expensive to change because it involves the creation of a copy.
Whereas mutable objects are easy to change.
- Use of mutable objects is recommended when there is a need to change the size or content of the object.
- Exception : However, there is an exception in immutability as well. We know that tuple in python is immutable. But the tuple consists of a sequence of names with unchangeable bindings to objects.
Consider a tuple.
- tup = ([3, 4, 5], ‘myname’)
The tuple consists of a string and a list. Strings are immutable so we can’t change its value. But the contents of the list can change. The tuple itself isn’t mutable but contain items that are mutable