Addressing the last element of a list

Steven D'Aprano steve at REMOVETHIScyber.com.au
Tue Nov 8 09:00:26 EST 2005


On Tue, 08 Nov 2005 01:31:31 -0800, pinkfloydhomer at gmail.com wrote:

> So there is no way in Python to make an alias for an object?

Yes, sort of. Bind two names to the same mutable object:

py> x = ["Something mutable"]
py> y = x
py> y.append("this way comes.")
py> print x
['Something mutable', 'this way comes.']

Note that this only works with mutable objects like lists and dicts, and
is a side effect of mutability, rather than a deliberate "alias".

In general, you can bind multiple names to the same object. The one liner

x = y = 1

is the same as the two liner

x = 1
y = x

Both create two names, x and y, and sets them both to the same int 1.

Because ints are immutable, if you rebind one name, the other one will
NOT change:

py> x += 1
py> print x, y
2, 1


-- 
Steven.




More information about the Python-list mailing list