[newbie] A question about lists and strings

Peter Otten __peter__ at web.de
Fri Aug 10 05:59:43 EDT 2012


Mok-Kong Shen wrote:

> 
> In an earlier question about lists, I was told about the issue of
> creation of local names in a function. However, I still can't
> understand why the program below outputs:
> 
> [999] sss
> [999]
> 
> and not two identical lines of output. For both operators "+=" should
> anyway work in similar manner in the function xx in my view.
> 
> Thanks for your help in advance.
> 
> M. K. Shen
> 
> ----------------------------------------------------------
> 
> def xx(list,str):
>    list+=[999]
>    str+="sss"

a += b

is internally translated into to

a = a.__iadd__(b)

If the 'list' class were implemented in Python it would look like

class list:
   def __iadd__(self, other):
       for item in other:
           self.append(item)
       return self

i. e. the original list is modified when you perform += and you'll see the 
modification when you look at any name bound to that original list:

b = a = [1, 2]
a += [3, 4]
print a # [1, 2, 3, 4]
print b # [1, 2, 3, 4]

Strings on the other hand are "immutable" -- they cannot be altered after 
the initial creation. The hypothetical __iadd__() implementation is

class str:
    def __iadd__(self, other):
        return self + other

So += rebinds a name to a new string:

b = a = "first"
a += "second"
print b # first
print a # firstsecond

Armed with this knowledge

> lista=[]
> stra=""
> lista+=[999]

[999] is appended to lista and lista is rebound to itself.

> stra+="sss"

A new string "" + "sss" is created and stra is bound to that new string.

> print(lista,stra)

 
> listb=[]
> strb=""
> xx(listb,strb)

Inside xx() 

(1) 999 is appended to listb and the local variable list is rebound.
(2) A new string "" + "sss" is created and bound to the local variable str.

> print(listb,strb)

If you have understood the above here's a little brain teaser:

>>> a = ([1,2,3],)
>>> a[0] += [4, 5]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment

>>> a[0]

What are the contents of a[0] now?





More information about the Python-list mailing list