As you probably know, Python slices like arr[1:3]
etc. do NOT provide a view onto list and instead creates a copy of the list, what can be not optimal performance if array is big and you make for example arr[1:]
(copies all exept first)
the idea of a view to an array is like :
class ylist_view():
def __init__(self,lst, begin, end):
self.list = lst
self.len = end - begin
self.begin = begin
self.end = end
def __getitem__(self, i):
if i<0: i += self.len
return self.list[self.begin + i]
def __setitem__(self, i,value):
if i<0: i += self.len
self.list[self.begin + i] = value
def __str__(self):
return '[' + ', '.join( str(self.list[i]) for i in range(self.begin, self.end)) + ']'
class inbox():
def __init__(self, value):
self.value = value
def __str__(self):
return '<' + str(self.value) + '>'
def __repr__(self):
return '<' + str(self.value) + '>'
a = [ inbox(x) for x in [1,2,3,4,5]]
b = a [1:3]
b[0] = 20 # creates a copy
print('list a is unchanged:', a)
print('b = a [1:3] is a copy of a :', b)
c = ylist_view(a,1,3)
c[0] = 20
print('ylist_view c is a view to a:', a)
Inbox class is a dummy class for illustration.
As you can see, b = a [1:3]
is a copy, whereas c = ylist_view(a,1,3)
references the original array.
Does it make sense to use this approach in a real Python project or there is some built-in in Python to do that?