Skip to content

Instantly share code, notes, and snippets.

@3noch
Last active June 20, 2023 12:01
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 3noch/b5f3175cfe39aea71ca4d07469570047 to your computer and use it in GitHub Desktop.
Save 3noch/b5f3175cfe39aea71ca4d07469570047 to your computer and use it in GitHub Desktop.
ListView.py
class ListView():
def __init__(self, items, slice_=None):
start = (slice_.start if slice_ else None) or 0
stop = (slice_.stop if slice_ else None) or float('inf')
step = (slice_.step if slice_ else None) or 1
if isinstance(items, ListView):
self._items = items._items
self._start = max(items._start, items._start + start)
self._stop = min(items._stop, items._start + stop)
self._step = items._step * step
else:
self._items = items
self._start = start
self._stop = stop
self._step = step
def __getitem__(self, key):
if isinstance(key, slice):
return ListView(self, key)
return self._items[self._start + key * self._step]
def __iter__(self):
return (self._items[i] for i in range(self._start or 0, len(self._items) if self._stop == float('inf') else self._stop, self._step))
def __len__(self):
return (min(len(self._items), self._stop) - self._start) // self._step
@3noch
Copy link
Author

3noch commented Aug 14, 2020

One thing we could do to make this more flexible is not use len and indexing in __iter__. Instead we could iterate and skip _step items. We'd have to keep around some sort of pointer to the first item to start iterating over. That would allow us to slice into things like generators!

@ruzrobert
Copy link

ruzrobert commented Apr 12, 2023

For the future: just adding where this script is referenced on StackOverflow

@devqqmao
Copy link

thank you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment