Addressing the last element of a list

Steven D'Aprano steve at
Tue Nov 8 15:08:34 CET 2005

On Tue, 08 Nov 2005 01:04:13 -0800, pinkfloydhomer at wrote:

> Or alternatively:
> Is there a way to make reference to the last element of a list, to use
> as a shorthand:
> ref := &lst[len(lst) - 1] # I know syntax is wrong, but you get the
> idea
> and then using the last element of the list by (assuming the element is
> a dict):
> ref["foo"] = 42
> ref["bar"] = "Ni!"

py> lst = ["Now is the time", 4, "all good men", {"foo": "bar"}]
py> lst[-1]  # refers to the last item of lst
{'foo': 'bar'}
py> obj = lst[-1]  # the name obj is now bound to the same dict
py> obj["foo"] = 42
py> print lst
['Now is the time', 4, 'all good men', {'foo': 42}]

This only works with mutable objects. See:

py> obj = lst[-3]
py> obj
py> obj = obj + 1  # rebinds the name obj, doesn't change the underlying
object the name points to
py> print lst
['Now is the time', 4, 'all good men', {'foo': 42}]

You will quickly learn what are mutable and what are immutable. Ints,
floats, longs, strs and tuples are immutable. Lists and dicts are mutable.
Custom classes could be either, in principle, but are generally mutable.


More information about the Python-list mailing list