Addressing the last element of a list
noway at sorry.com
Tue Nov 8 12:04:30 CET 2005
pinkfloydhomer at gmail.com 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["pos"][-4], that might be
One simple workaround:
def createAlias(L, idx1, idx2, idx3):
L[idx1][idx2][idx3] = n
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["pos"], and that would be a well defined object with a method setThis()
which will modify the moral equivalent of [-4].
More information about the Python-list