Addressing the last element of a list

Giovanni Bajo noway at
Tue Nov 8 12:04:30 CET 2005

pinkfloydhomer at wrote:

> I just want an alias.

What you want is impossible. But there are many workarounds.

> I just want to be able to make a reference to any old thing in Python.
> A list, an integer variable, a function etc. so that I, in complicated
> cases, can make a shorthand. If "myRef" could somehow "point at"
> something long an complicated like a[42]["pos"][-4], that might be
> useful.

One simple workaround:

def createAlias(L, idx1, idx2, idx3):
     def setval(n):
         L[idx1][idx2][idx3] = n
     return setval

k = createAlias(a, 42, "pos", -4)


n = computeValue(...)
k(n)   # store it!

You will also find out that your case is actually very unlikely in
well-designed code. You don't usually work with stuff with three level of
nesting like a[][][], since it gets totally confusing and unmaintanable. You
will end up always with objects with better semantic, and methods to modify
them. So in the end you will always have a reference to the moral equivalent of
a[42]["pos"], and that would be a well defined object with a method setThis()
which will modify the moral equivalent of [-4].
Giovanni Bajo

More information about the Python-list mailing list