[newbie] A question about lists and strings

Dave Angel d at davea.name
Fri Aug 10 06:53:19 EDT 2012


On 08/10/2012 06:31 AM, Mok-Kong Shen wrote:
> Am 10.08.2012 12:07, schrieb Dave Angel:
> [snip]
>> At this point, in top-level code, the listb object has been modified,
>> and the strb one has not;  it still is bound to the old value.
>
> This means there is no way of modifying a string at the top level
> via a function, excepting through returning a new value and assigning
> that to the string name at the top level. Please again correct me, if
> I am wrong.
>
> M. K. Shen
>

You're close.  There are three ways I can think of. The "right" way is
to return a value, which the caller can use any way he wants, including
binding it to a global.
    
Second is to declare the name as global, rather than taking the object
as a formal parameter.  In this case, you're taking on the
responsibility for managing that particular global, by its correct name.
    def yy():
        global strb
        strb += "whatever"

Third is to hold the string in some more complex structure which is
mutable.  (untested, may contain typos)
    def  zz(mydict):
          mydict["key1"] += "text"

called as:
globaldict = {"key1": "initial ", "key2": "init"}




-- 

DaveA




More information about the Python-list mailing list