List &reference to segment of another list. Can dis be done?

Jeff Epler jepler at unpythonic.net
Wed May 29 16:36:54 EDT 2002


You could create a list-like object which is created with a slice from
another list
    class ReferenceList:
	def __init__(self, l, start, end = None):
	    self.l = l
	    self.start = start
	    if end is None: end = len(l)
	    self.end = end

then, you could override __getitem__ and __setitem__ to use the
underlying list

	def __getitem__(self, i):
	    if self.start + i >= self.end: raise IndexError
	    return self.l[self.start + i]

	def __setitem__(self, i, v):
	    if self.start + i >= self.end: raise IndexError
	    self.l[self.start + i] = v

(now you'll need to make stuff like slices work right .. tall order!)

>>> li = [0, 1, 2, 4, 8]
>>> re = ReferenceList(li, 2)
>>> re[0] = 16
>>> re[1] = 32
>>> re[2] = 64
>>> print li
[0, 1, 16, 32, 64]

However, because 'name = value' is a binding operation (not a mutating
one), you can't ever make
    re = [16, 32, 64]
change the value of the object "re" used to name.  This is an
oft-discussed subject, and I'll leave it to my betters to explain it.

Jeff





More information about the Python-list mailing list