By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
443,400 Members | 903 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 443,400 IT Pros & Developers. It's quick & easy.

a=([],); a[0]+=[1]

P: n/a
When reading about python "warts" i stepped in this
example I find quite puzzling:

a = ( [] , )
a[0] += [1]

this gives an error, because a tuple cannot be
modified. But if you print the content of "a"
it will show it has indeed been modified.

How can this happen ? if "+=" for list was called
then no modification to the tuple was requested and
so no error should have been raised; if instead "+"
and "=" was executed then after a failing assignment
the original list is safe... (or at least I thought
so; if you type "a[0] = [2]" you get the error and
"a" is not modified).

Is there an explanation simpler than investigating
on python sources ?

Andrea
Jul 18 '05 #1
Share this Question
Share on Google+
1 Reply


P: n/a
Andrea Griffini <ag****@tin.it> wrote in
news:7f********************************@4ax.com:
When reading about python "warts" i stepped in this
example I find quite puzzling:

a = ( [] , )
a[0] += [1]

this gives an error, because a tuple cannot be
modified. But if you print the content of "a"
it will show it has indeed been modified.

How can this happen ? if "+=" for list was called
then no modification to the tuple was requested and
so no error should have been raised; if instead "+"
and "=" was executed then after a failing assignment
the original list is safe... (or at least I thought
so; if you type "a[0] = [2]" you get the error and
"a" is not modified).

Is there an explanation simpler than investigating
on python sources ?


+= is implemented by calling the __iadd__ method (if it exists, otherwise
__add__ is called). In either case the result of the method is then
assigned to the destination.

So what is happening here is that list.__iadd__ modifies the list in place,
but then the attempt to assign the result into the tuple fails.

Although __iadd__ extends the list in place this need not be true for all
types. An object could have an implementation for inplace addition that
actually creates a new object, so Python cannot optimise out the store.

See http://groups.google.co.uk/groups?th...EBE%40noaa.gov
for a (long) discussion of this topic.
Jul 18 '05 #2

This discussion thread is closed

Replies have been disabled for this discussion.