Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.