Skip to content

Instantly share code, notes, and snippets.

@yegle
Last active August 29, 2015 14:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yegle/af51f08ef289bdffbc7f to your computer and use it in GitHub Desktop.
Save yegle/af51f08ef289bdffbc7f to your computer and use it in GitHub Desktop.
Create reference slice to a list in Python
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
class MyList(list):
def __init__(self, raw_list, start=None, stop=None):
self.raw_list = raw_list
self.start = start or 0
self.stop = stop or len(raw_list)-1
def __getitem__(self, slice_):
return MyList(self.raw_list, start=self.start+slice_.start,
stop=self.start+slice_.stop)
def __setitem__(self, slice_, value):
self.raw_list[slice_] = value
def __str__(self):
return str(self.raw_list[self.start:self.stop])
def foo(l):
l[:] = [999]
if __name__ == '__main__':
l = [1, 2, 3, 4]
ref_copy = MyList(l)
ref_copy[0] = 999
assert l == [999, 2, 3, 4]
foo(l)
assert l == [999]
l[:] = [1, 2, 3, 4, 5, 6]
assert str(ref_copy[1:3]) == str([2, 3])
assert str(ref_copy[1:3][1:2]) == str([3])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment