[newbie] A question about lists and strings

Roman Vashkevich vashkevichrb at gmail.com
Fri Aug 10 05:48:14 EDT 2012


10.08.2012, в 13:28, Roman Vashkevich написал(а):

> 10.08.2012, в 13:19, Mok-Kong Shen написал(а):
> 
>> 
>> 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"
>> 
>> lista=[]
>> stra=""
>> lista+=[999]
>> stra+="sss"
>> print(lista,stra)
>> 
>> listb=[]
>> strb=""
>> xx(listb,strb)
>> print(listb,strb)
>> -- 
>> http://mail.python.org/mailman/listinfo/python-list
> 
> It seems like your xx() function doesn't return local str parameter and prints the global empty str, whereas it mutates the global list.
> 
> Roman

Excuse me for the mess I just did in my message:)
The function doesn't print anything of cause. It takes list by reference and creates a new local str.
When it's called with listb and strb arguments, listb is passed by reference and mutated. A string "sss" is concatenated with an empty local str. Nothing more happens. Since local str is not returned by xx(), it can not be expected to be printed out in the statement that follows. What is printed out in the print statement is the mutated listb and the global strb.

RV


More information about the Python-list mailing list