Addressing the last element of a list

Michael ms at cerenity.org
Tue Nov 8 18:47:39 EST 2005


pinkfloydhomer at gmail.com wrote:

> Is there a way to make reference to the last element of a list, to use
> as a shorthand:

Yes. It's not wise to use, since this is brittle and will fail hard for you,
but since you're interested, this is how you /could/ do it: (largely)

# First of all create a mechanism for creating and handling symbolic
# references
class ref(object):
    def __init__(self, val):
        self._val = val
    def set_val(self, val):
        exec("global %s\n%s = %s" % (self._val, self._val, repr(val)))
    def get_val(self):
        return eval(self._val)
    val = property(get_val, set_val)

Now we can play with this.

Note the word *PLAY* .

>>> lst = ["1","2","3","4"]
>>> y = ref("lst[-1]")
>>> y.val
'4'
>>> y.val = 10
>>> y.val
10
>>> lst
['1', '2', '3', 10]
>>> i = 1
>>> z = ref("i")
>>> z.val = 10
>>> i
10

Once again, note the word *play* - don't use this in __anything__ :-)
Python binds values to names. As a result what you're after when asking
for 

ref := &lst[len(lst) - 1]

And then for ref to actually refer to that last item, you have to realise
that you're asking for an indirection on the name "lst[-1]". Short of doing
silly things with eval and exec (which you really don't want to do), you
can't do this.

However, it's python, so of course you *can*, but just because you *can* do
something doesn't mean that you *should*.

You'll note that in order to make the reference to the plain mutable
value (i) work the set_val had to mark the value as global, which isn't
quite right. (You might be able to trick it into using the "right" scope
using lambda somehow, maybe)

Once again, don't use it! (hopefully of interest though)

Regards,


Michael.
--
http://kamaelia.sourceforge.net/




More information about the Python-list mailing list