This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

Author Theo.Julienne
Recipients Theo.Julienne, asdfasdfasdfasdfasdfasdfasdf, benjamin.peterson, giampaolo.rodola, loewis, r.david.murray, rhettinger
Date 2010-08-27.23:10:12
SpamBayes Score 8.638035e-12
Marked as misclassified No
Message-id <1282950613.94.0.212653213805.issue9702@psf.upfronthosting.co.za>
In-reply-to
Content
def list_again(foo):
	foo.append("bar")

def list_again_again(foo):
	foo = foo + ["1"]


The part that can be confusing is that 'foo' is a *copy* of a *reference* to an object. Because 'foo' is a copy, assigning to it will only alter a local copy, while calling methods on it will always call on the original object (because it's a reference to the same place). When an object is mutable, it just has no methods that modify it, so the only way to change it is by assignment, which will never result in changes to the outside function. There are no special cases, but it does require understanding pass-by-(copy/reference) and object mutability, and is against most people's intuitions.

The way that behaves is actually how most *programmers* would expect (because they are used to it), though. Every other language I can think of does it this way. For example, in C, a pointer is still a copy of a reference -- if you assign to the pointer, it wont propagate up to the caller. The same goes in Java.

Perhaps what makes it harder to understand in Python is that everything is an object and looks the same regardless of mutability, whereas other languages typically have conventions (such as capitalising: int, str, Dict, List) to make it clearer when something is an object (which usually means the same as a python mutable object) as opposed to a built-in type (which usually means the same as a python immutable object).

Just my 2c
History
Date User Action Args
2010-08-27 23:10:14Theo.Juliennesetrecipients: + Theo.Julienne, loewis, rhettinger, giampaolo.rodola, benjamin.peterson, r.david.murray, asdfasdfasdfasdfasdfasdfasdf
2010-08-27 23:10:13Theo.Juliennesetmessageid: <1282950613.94.0.212653213805.issue9702@psf.upfronthosting.co.za>
2010-08-27 23:10:12Theo.Juliennelinkissue9702 messages
2010-08-27 23:10:12Theo.Juliennecreate