Home > Article > Backend Development > Is the set collection in python a variable type?
What is a mutable/immutable object
Immutable object, the value in the memory pointed to by the object cannot be changed. When a variable is changed, since the value it points to cannot be changed, it is equivalent to copying the original value and then changing it. This will open up a new address, and the variable will point to this new address.
Variable object, the value in the memory pointed to by the object can be changed. When a variable (reference to be precise) is changed, the value it refers to is actually changed directly. No copying occurs, and no new address is opened. In layman's terms, it is changed in place.
In Python, numeric types (int and float), string str, and tuple tuple are all immutable types. Lists, dictionaries, and sets are variable types.
It is more intuitive to look at the code. Look at the code of the set collection:
abb = {1, 2, 3} acc = abb print(id(abb), id(acc)) acc.add(4) print(abb) # {1, 2, 3, 4} print(id(abb), id(acc)) # 相等
The variable object can be modified because the pointed object can be modified, so There is no need to make a copy and then change it, just change it in place, so no new memory will be opened, and the id will remain unchanged before and after the change.
Of course, this is not the case for immutable objects. You can compare it with this
abc = 3 dd = abc dd = 43 print(abc) # 3,并不随dd的改变而改变
But if it is a copy, it only copies the content and does not transfer it without reference. This is especially useful when you want to use the values of a list without modifying the original list.
blist = alist[:] # or alist.copy() print(alist is blist) # False blist.append(4) print(alist) # 还是[1,2 ,3]没有变化
The above is the detailed content of Is the set collection in python a variable type?. For more information, please follow other related articles on the PHP Chinese website!