Chris Chris - 1 year ago 73
Python Question

Slicing a list in Python without generating a copy

I have the following problem.

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

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

Answer Source

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])
>>> id(b[0])
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download