'Why does using slice notation work for copying lists but not other sequences?

If I want to copy a list object I can do the following:

colours = ['blue', 'red', 'yellow']
colours_copy = colours[:]

However when I do the same with a string and compare IDs both variables seem to be pointing to the same object:

string = 'lion'
new_string = string[:]
print(id(string))
print(id(new_string))

Output:

2397445995824
2397445995824

Why is this?

Thanks!



Solution 1:[1]

These are some optimizations made by Cpython. For immutable objects like string , tuple and so on, shallow copies of them will get themselves. It often have no impact on users, isn't it?

Note, though, that if there are mutable objects in the tuple, the shallow copy will get themselves, but the deep copy will get a new object:

>>> a = (1, 2)
>>> a is a[:]
True
>>> from copy import deepcopy
>>> a is deepcopy(a)
True
>>> a = ({1, 2},)
>>> a is a[:]
True
>>> a is deepcopy(a)
False

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Mechanic Pig