Effect of Update v.s. Reassign in Python
1 min readJan 14, 2018
This post demonstrates behaviors of reassgin(e.g. x = x + 1
) v.s. update (e.g. x += 1
) in Python.
For primative types (e.g., int
), both reassign and update get a new id.
x = 1old_id = id(x)x = x + 1new_id = id(x)old_id == new_idFalsex = 1old_id = id(x)x += 1new_id = id(x)old_id == new_idFalse
But for a list, only update gets a new id, but not reassign.
x = [1]old_id = id(x)x += [2]new_id = id(x)x, old_id == new_id([1, 2], True)x = [1]old_id = id(x)x = x + [2]new_id = id(x)x, old_id == new_id([1, 2], False)Need to be aware of this difference to make list behave as expected. Compare below:Reassign `x`, where `y` is not updated:x = [1]y = [x]print(y)x = x + [2]print(y)[[1]]
[[1]]Update `x`, where `y` is also updated:x = [1]y = [x]print(y)x += [2]print(y)[[1]]
[[1, 2]]Same comparison for set in stead of list:
Reassign:
x = set([1])y = [x]print(y)x = x | set([1])print(y)[{1}]
[{1}]Update:x = set([1])y = [x]print(y)x |= set([2])print(y)[{1}]
[{1, 2}]
Code is here: https://github.com/yang-zhang/yang-zhang.github.io/blob/master/coding/reassign_vs_update.ipynb