我真的在改变列表吗?
Am I really mutating the list?
假设我有一个列表
lst1 = [1,2,3,4]
removed_item = lst1.pop()
lst1.append(removed_item)
我暂时更改了值,但是在 运行 之后我将一切恢复正常。这是否考虑改变列表?
是的,你这样做了,因为你删除了一个项目(改变列表)然后重新附加它(再次改变列表......)。
列表是可变的而字符串不是。 运行这个代码,你会得到答案
lst1 = [1,2,3,4]
print(id(lst1))
removed_item = lst1.pop()
print(id(lst1))
lst1.append(removed_item)
print(id(lst1))
str1 = "a string"
print(id(str1))
removed_item = str1[-1]
str1 = str1[:-1]
print(id(str1))
str1 += removed_item
print(id(str1))
假设我有一个列表
lst1 = [1,2,3,4]
removed_item = lst1.pop()
lst1.append(removed_item)
我暂时更改了值,但是在 运行 之后我将一切恢复正常。这是否考虑改变列表?
是的,你这样做了,因为你删除了一个项目(改变列表)然后重新附加它(再次改变列表......)。
列表是可变的而字符串不是。 运行这个代码,你会得到答案
lst1 = [1,2,3,4]
print(id(lst1))
removed_item = lst1.pop()
print(id(lst1))
lst1.append(removed_item)
print(id(lst1))
str1 = "a string"
print(id(str1))
removed_item = str1[-1]
str1 = str1[:-1]
print(id(str1))
str1 += removed_item
print(id(str1))