How do I do this? (eval() on the left hand side)

Steven Bethard steven.bethard at
Tue Dec 7 16:39:04 EST 2004

It's me wrote:
> How do I do something like this:
> I know that
>     a = 3
>     y = "a"
>     print eval(y)
> would give me a print out of 3 - but how do I do something to the effect of:
>     eval(y) = 4    # hopefully the value of a gets changed to 4

Generally, if you find yourself doing this, you may want to rethink your 
program organization.  That being said, if you are in the global scope, 
one option looks something like:

 >>> a = 3
 >>> y = 'a'
 >>> globals()[y] = 4
 >>> a

If you can give us some more context on why you want to do this, we can 
probably suggest a better approach.  There aren't too many places where 
even advanced Python programmers need to use eval...


More information about the Python-list mailing list