immutability
An immutable datatype, has the property that the value of an object never changes once constructed. The downside of immutability is that a new object must be created for every value.
Python immutable data type
- int, float, long, complex
- str
- bytes
- tuple
- frozen set
Python mutable data type
- byter array
- list
- set
- dict
Difference between i+=1
and i=i+1
method | return value | immutable object | mutable object | |
---|---|---|---|---|
i+=1 | iadd | the object that was muted | two methods are the same(because the old instance can't be muted, so a new one has to be created) | change the object inplace and return the muted object |
i=i+1 | add | a new instance of sth | two methods are the same | create a new instance and return the new instance reference |
Example
a = [1, 2, 3]
b = a
b += [1, 2, 3]
print a #[1, 2, 3, 1, 2, 3]
print b #[1, 2, 3, 1, 2, 3]
a = [1, 2, 3]
b = a
b = b + [1, 2, 3]
print a #[1, 2, 3]
print b #[1, 2, 3, 1, 2, 3]
网友评论