Slicing in Python always create a new object. You can test it with a list of integers..
>>> a = [254, 255, 256, 257, 258]
>>> b = [254, 255, 256, 257, 258]
>>> for i in range(5): print(a[i] is b[i])
...
True
True
True
False
False
In Python, integers in the range [-5, 256] are statically constructed in the interpreter and refer to fixed instances of objects. All other integers are created dynamically and refer to a new object each time they are created. >>> x = 257
>>> y = 257
>>> x is y
False
>>> def f():
... x = 257
... y = 257
... return x is y
...
>>> f()
True
The lesson being that `is` is essentially meaningless for immutable objects, and to always use `==`.OTOH it’s recommended to use `is` rather than `==` when comparing to “singletons like `None`”.
https://www.python.org/dev/peps/pep-0008/#programming-recomm...
class C:
def __eq__(self, other):
return True
print(C() == None) # True
print(C() is None) # FalseIt always creates a new object but it doesn't necessarily copy the contents (even shallowly).
For instance slicing a `memoryview` creates a subview which shares storage with its parent.
Since you said "always", I'll be "that guy"...
For the builtin types, yeah. But not in general; user code can do whatever it wants:
class MyType:
def __getitem__(self, *args):
return self
my_obj = MyType()
my_other_obj = my_obj[3:7]
assert my_other_obj is my_obj