7

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.

poke
  • 369,085
  • 72
  • 557
  • 602
augurar
  • 12,081
  • 6
  • 50
  • 65
  • 1
    Related - http://stackoverflow.com/questions/3485475/can-i-create-a-view-on-a-python-list Not sure if something has come up in the intervening years, so not voting to close as a duplicate :-) – Sean Vieira Feb 18 '15 at 02:41
  • Could you specify what answers do you expect other than the provided in the linked question: custom Slice class, numpy, memoryview, generator (iterator)? – jfs Feb 18 '15 at 03:01

1 Answers1

2

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
volcano
  • 3,578
  • 21
  • 28
  • 1
    `islice` doesn't actually produce an indexable sequence - you need to materialize the iterator, at which point it will no longer be a view into the underlying sequence, but rather it's own sequence. – Sean Vieira Feb 18 '15 at 02:44