Addressing the last element of a list

Steven D'Aprano steve at
Tue Nov 8 15:22:37 CET 2005

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

> But if lst[42]["pos"] happens to hold an integer value, then
> a = lst[42]["pos"]
> will _copy_ that integer value into 'a', right? Changing 'a' will not
> change the value at lst[42]["pos"]

Not quite. Don't think of Python names as being like variables.

Think of it like this: in Python, everything is an object. You reference
objects by creating a name, and binding that name to an object:

py> parrot = {'feathers': 'beautiful plumage'}

This creates a name, parrot, and binds it to the dictionary given.

If the underlying object is mutable, like dicts and lists, you can modify
the object in place:

py> parrot['state'] = 'pining for the fjords'
py> parrot['breed'] = 'Norwegian Blue'
py> print parrot
{'feathers': 'beautiful plumage', 'state': 'pining for the fjords',
'breed': 'Norwegian Blue'}

But immutable objects can't be changed in place (that's what immutable
means). Ints are immutable objects, so you can't change the value of the
int object 1: 1 is always 1.

(Imagine the confusion if you changed the object 1 to have a value of 3;
you could say 1 + 2 and get 5. That would be a *really* bad idea.)

So when working with ints, strs or other immutable objects, you aren't
modifying the objects in place, you are rebinding the name to another

py> spam = "a tasty meat-like food"
py> alias = spam  # both names point to the same str object
py> spam = "spam spam spam spam"  # rebinds name to new str object
py> print spam, alias
'spam spam spam spam' 'a tasty meat-like food'


More information about the Python-list mailing list