assignment to reference

Fredrik Lundh fredrik at pythonware.com
Wed Oct 26 06:27:50 EDT 2005


Loris Caren wrote:

> a = 'apple'
> b = 'banana'
> c = 'cabbage'
>
> How can I get something like:-
>
> for i in 'abc':
>     r = eval(i)
>     if r == 'cabbage': r = 'coconut'
>
> actually change the object referenced by r rather
> than creating a new object temporarily referenced by it?

if you need a container, you should use a container object instead of
the local namespace.  in this case, a dictionary is what you want:

    stuff = {
        'a': 'apple',
        'b': 'banana',
        'c': 'cabbage'
    }

    for i in "abc":
        if stuff[i] == "cabbage":
            stuff[i] = "coconut"

(tweak as necessary)

</F>






More information about the Python-list mailing list