1

I am confused about the slice operation.

>>> s = "hello world"
>>> y = s[::]
>>> id(s)
4507906480
>>> id(y)
4507906480 # they are the same - no new object was created

>>> z = s[:2]
>>> z
'he'
>>> id(z)
4507835488 # z is a new object

What allocation rule does slice operation follow?

codeforester
  • 39,467
  • 16
  • 112
  • 140
  • 2
    Whatever rule the object says it should. – user2357112 May 14 '18 at 20:12
  • 3
    Looks like a sensible optimization to me since making an exact copy of an immutable object can't have all that many use cases. – Paul Panzer May 14 '18 at 20:14
  • 1
    @PaulPanzer Yeah, the compiler makes a similar optimization if you have two provably-immutable constants with the same value in the same compilation unit, and the interpreter makes a similar optimization with small strings in the same subinterpreter and small ints and the "keyword constants" like None anywhere in the process. And of course that differs between Python implementations and versions. In general, any code that relies two equal immutable values either being identical or not being identical is broken. – abarnert May 14 '18 at 20:40

1 Answers1

5

For most built-in types, slicing is always a shallow copy... in the sense that modifying the copy will not modify the original. This means that for immutable types, an object counts as a copy of itself. The copy module also uses this concept of "copy":

>>> t = (1, 2, 3)
>>> copy.copy(t) is t
True

Objects are free to use whatever allocation strategy they choose, as long as they implement the semantics they document. y can be the same object as s, but z cannot, because s and z store different values.

user2357112
  • 260,549
  • 28
  • 431
  • 505
  • 1
    I think `memoryview` is the only exception among builtin types, but it might be worth giving an example of a more common exception, like numpy arrays, even though they aren't builtin. – abarnert May 14 '18 at 20:33
  • Is it correct to think of this like (string) interning? – Chris_Rands May 15 '18 at 21:39
  • 1
    @Chris_Rands: A little, in that it involves object reuse, but it's different in that we're not looking objects up in a central table of canonical representatives. – user2357112 May 15 '18 at 22:16