Chris Chris - 27 days ago 9
Python Question

Slicing a list in Python without generating a copy

I have the following problem.


Given a list of integers
L
, I need to generate all of the sublists
L[k:]
for k in [0, len(L) - 1]
, without generating copies.


How do I accomplish this in Python? With a buffer object somehow?

Answer

Slicing lists does not generate copies of the objects in the list; it just copies the references to them.

I had a moment of uncertainty about immutable objects; but I checked and indeed, only the reference is copied:

>>> a = [1, 2, 3]
>>> b = a[1:3]
>>> id(a[1])
143727964
>>> id(b[0])
143727964