预计阅读本页时间:-
Immutable Types Can’t Be Changed In-Place
You can’t change an immutable object in-place. Instead, you construct a new object with slicing, concatenation, and so on, and assign it back to the original reference, if needed:
T = (1, 2, 3)
T[2] = 4 # Error!
T = T[:2] + (4,) # OK: (1, 2, 4)
广告:个人专属 VPN,独立 IP,无限流量,多机房切换,还可以屏蔽广告和恶意软件,每月最低仅 5 美元
That might seem like extra coding work, but the upside is that the previous gotchas can’t happen when you’re using immutable objects such as tuples and strings; because they can’t be changed in-place, they are not open to the sorts of side effects that lists are.