Python3: Mutable, Immutable... everything is object!
what is id and type?
id() is an inbuilt function in Python.
Syntax:
id(object)
As we can see the function accepts a single parameter and is used to return the identity of an object, if we relate this to C, then they are actually the memory address, here in Python it is the unique id.
Example.
str1 = "Sonic"
print(id(str1))
str2 = "Sonic"
print(id(str2))
# This will return True
print(id(str1) == id(str2))"
Output:
140252505691448
140252505691448
True
type() method returns class type of the argument(object) passed as parameter. type() function is mostly used for debugging purposes. Two different types of arguments can be passed to type() function, single and three argument. If single argument type(obj) is passed, it returns the type of given object. If three arguments type(name, bases, dict) is passed, it returns a new type object.
Syntax :
type(object
type(name, bases, dict)
string = "hi, my friend"
num = 20
dec = 20.5
type(string)
type(num)
type(dec)
Output:
str
int
float
Mutable and inmutable objects
Mutables are objects that, once created, can change their state in the future.
Python treats mutable and immutable types differently, and if you don't understand this concept well, you can get unexpected behavior in your programs. The easiest way to see the difference is to use lists as opposed to tuples. The former are mutable, the latter are not. A list l can be modified once it is created.
Example of mutables objects.
The immutable ones are the simplest to use in programming (they are usually the simple data types: String, Integer, Boolean, etc.) because they do exactly what they are expected to do at each moment, and paradoxically, to work like this, they are the ones that most they punish memory (they are not optimized to take up less memory when copied, and degrade more memory lifespan when written more times).
An immutable object once created, as its name suggests, its state cannot change once it has been created. But if I have changed String or int values many times after creating them? In appearance, but they do not change anything and I will explain it to you below (I suggest that as you read each of the next paragraphs you look at the image that accompanies it below; in the following images you read first from the left the "Console of Python” with a green arrow indicating the line of code added, and then the part on the right with the memory and its occupants).
Example of inmutables.