assignment to reference

Sybren Stuvel sybrenUSE at YOURthirdtower.com.imagination
Wed Oct 26 06:26:12 EDT 2005


Loris Caren enlightened us with:
> If
>
> 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?

Use:

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

for key, value in x.iteritems():
    if value == 'cabbage':
        x[key] = 'coconut'

NOTE: I haven't tested this code

> I've tried playing with eval and exec without the desired effect.

If you notice yourself using such functions, it's ususally a lot
better to simply stash your data in a dictionary, and use that
instead.

Sybren
-- 
The problem with the world is stupidity. Not saying there should be a
capital punishment for stupidity, but why don't we just take the
safety labels off of everything and let the problem solve itself? 
                                             Frank Zappa



More information about the Python-list mailing list