Augmented Assignment question

Duncan Booth duncan at NOSPAMrcp.co.uk
Fri Jul 18 11:08:03 EDT 2003


Robin Munn <rmunn at pobox.com> wrote in 
news:slrnbhg1vg.1sg.rmunn at localhost.localdomain:

> Notice how the id remained the same in list augmented assignment, while
> it changed in tuple augmented assignment. That's because in the first
> example, l is not rebound; instead, the list object that l points to
> gets extended. In the second example, t gets rebound to a *new* tuple
> object. Another demonstration:

Pedantically speaking, l does get rebound. It just happens that it gets 
rebound to the same object which is also mutated. It can be significant in 
cases where you are not allowed to rebind the value e.g.

>>> a = [1, 2, 3]
>>> b = [a]
>>> b[0] += [4]
>>> b
[[1, 2, 3, 4]]
>>> a
[1, 2, 3, 4]
>>> a = [1, 2, 3]
>>> b = (a,)
>>> b[0] += [4]
Traceback (most recent call last):
  File "<pyshell#7>", line 1, in ?
    b[0] += [4]
TypeError: object doesn't support item assignment
>>> b
([1, 2, 3, 4],)


-- 
Duncan Booth                                             duncan at rcp.co.uk
int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3"
"\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure?




More information about the Python-list mailing list