Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python slice without copy? [duplicate]

Is there a way to create a "slice view" of a sequence in Python 3 that behaves like a regular slice but does not create a copy of the sliced part of the sequence? When the original sequence is updated, the "slice view" should reflect the update.

>>> l = list(range(100))
>>> s = Slice(l, 1, 50, 3)  # Should behave like l[1:50:3]
>>> s[1]
4
>>> l[4] = 'foo'
>>> s[1]  # Should reflect the updated value
'foo'

I can write my own Slice class that does this but I wanted to find out if there was a built-in way.

like image 441
augurar Avatar asked Feb 18 '15 02:02

augurar


People also ask

Does Python slice make a copy?

The short answer. Slicing lists does not generate copies of the objects in the list; it just copies the references to them. That is the answer to the question as asked.

Does slice create a copy?

The slice() method is a copying method. It does not alter this but instead returns a shallow copy that contains some of the same elements as the ones from the original array.

Does slice create a deep copy?

slice() , Array. from() , Object. assign() , and Object. create() ) do not create deep copies (instead, they create shallow copies).

Does slicing copy array?

The slice() method can be used to create a copy of an array or return a portion of an array. It is important to note that the slice() method does not alter the original array but instead creates a shallow copy.


1 Answers

Use islice from itertools library

EDIT:

I see where I misunderstood the question. Well, there is no such thing. If you want to create your class, you'll have to:

  1. Keep a reference to the original list in you Slice class
  2. Define, __iter__, __getitem__ and __setitem__ methods to work on the original list with index conversion
like image 120
volcano Avatar answered Sep 28 '22 05:09

volcano