ref to a list index

Alex Martelli aleax at aleax.it
Sat Mar 15 03:09:40 EST 2003


Erik Lechak wrote:

> Hello all,
> 
> I know lists are mutable and ints are not.  Is there a way to
> reference an index of a list.
> 
> This is what happens, and I understand why:
> x = [1,2,3,4,5]
> element = x[2]
> element = 6
> print x
>>>> [1,2,3,4,5]
> 
> Is it possible to do the following (I will use a litter "pseudo perl
> syntax magic" to highlight my question)?
> 
> x = [1,2,3,4,5]
> element = \x[2] # I want element to be a ref to the 2nd index of
> element = 6     # array x, not a ref to the int at that index
> print x
>>>> [1,2,6,4,5]

I don't follow your following "desired use case", but, to answer
the questions you just posed:

there is *NO* way to make simple assignment to a bare name to anything
else than rebind that bare name.

so, there is no way you can use the exact syntax:

element = 6

to do anything else than rebind name 'element' to the value 6, whatever
object name 'element' was previously bound to.

There are many ways to perform the task you want, but with different 
syntax sugar than by assignment to a bare name.  For example:

class RefIntoList(object):
    def __init__(self, alist, anindex):
        self.alist = alist
        self.anindex = anindex
    def getval(self):
        return self.alist[self.anindex]
    def setval(self, value):
        self.alist[self.anindex] = value

then:

element = RefInfoList(x, 2)
element.setval(6)

if you like the equal-sign a lot you can add a property to the class:

    val = property(getval, setval)

and then you can use

element.val = 6

as entirely equivalent to

element.setval(6)


Note that this is an assignment to an ATTRIBUTE of element, NOT to
a bare name: this makes a big difference.


Alex





More information about the Python-list mailing list