Just curious more than anything why python will allow me to update a slice of a list but not a string?
开发者_运维问答>>> s = "abc"
>>> s[1:2]
'b'
>>> s[1:3]
'bc'
>>> s[1:3] = "aa"
>>> l = [1,2,3]
>>> l[1:3]
[2, 3]
>>> l[1:3] = [9,0]
>>> l
[1, 9, 0]
Is there a good reason for this? (I am sure there is.)
Because in python, strings are immutable.
Python distinguishes mutable and immutable data types. Making strings immutable is a general design decision in Python. Integers are immutable, you can't change the value of 42
. Strings are also considered values in Python, so you can't change "fourty-two"
to something else.
This design decision allows for several optimisations. For example, if a string operation does not change the value of a string, CPython usually simply returns the original string. If strings were mutable, it would always be necessary to make a copy.
精彩评论