-2

I read that slicing of list returns a new list with the contents of the original list. While running the following code why am I seeing the same id for all the list returned by slicing. Can someone explain what is happening here.

list_4 = [0, 1, 2, 3, 4, 5]
print(id(list_4))
print(id(list_4[0:1]))
print(id(list_4[0:2]))
print(id(list_4[-1:]))

Output:

2812068811464
2812100759880
2812100759880
2812100759880
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
Harish Babu
  • 311
  • 2
  • 9
  • because `id` only guarantees a unique number *for the lifetime of the object*. IN each case here, your new list gets reclaimed immediately (CPython implementation detail) and the private heap is free to re-use that memory to allocate a new list (again, CPython implementation detail) – juanpa.arrivillaga Dec 01 '19 at 07:19

1 Answers1

2

Your slice got deleted before the next statement, so the new slice has the same id. If you keep the slice, the id is never the same:

>>> print(id(list_4[0:1]))
139887348117232
>>> print(id(list_4[0:2]))
139887348117232
>>> print(id(list_4[-1:]))
139887348117232
>>> b = list_4[0:1]
>>> c = list_4[0:2]
>>> id(b)
139887348117232
>>> id(c)
139887348207200
>>> 
lenik
  • 23,228
  • 4
  • 34
  • 43