Python slice without copy?

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 ​​portion 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 is a built-in way.

+6
source share
1 answer

Use islice from the itertools library

EDIT:

I see where I misunderstood the question. Well, that doesn't happen. If you want to create your own class, you need to:

  • Keep a reference to the source list in the Slice class
  • Define __iter__, __getitem__ and __setitem__ methods for working with the source list with index conversion.
+2
source

Source: https://habr.com/ru/post/982657/


All Articles