[Tutor] how to make a reference to part of list?

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Mon Oct 2 17:37:22 CEST 2006


> for example, I want to mutate part of a list, of course, I can achieve 
> this by passing the pair list and (begin, end) as parameters. but in 
> some case, this manner is quite tedious and in efficient

I'm not sure what you mean by "inefficient".  What do you think a 
"pointer" is, if not what you just described?  *grin*


Conceptually, a pointer is some arrow directed at some other thing. Here's 
a possible implementation of what you're asking:

###########################################################
class ListPointer:
     def __init__(self, L, i):
         """Creates a pointer into the i'th element of L."""
         self.L = L
         self.i = i

     def deref(self):
         """Returns the value pointed to."""
         return self.L[self.i]

     def mutate(self, value):
         """Mutates the list value that we point to."""
         self.L[self.i] = value
###########################################################


For example:

#####################################
>>> l = ["hello", "world", "testing"]
>>> p = ListPointer(l, 1)
>>> p.deref()
'world'
>>> p.mutate("universe")
>>> p.deref()
'universe'
>>> l
['hello', 'universe', 'testing']
#####################################

At the moment, this class allows point mutations, and could probably be 
adjusted to work with slices.


That being said, can you explain what the purpose is?  There may be some 
other effective way to do what you're trying to do, without the additional 
level of indirection that pointers impose.


More information about the Tutor mailing list