I want to do the following:
a = 1
b = 2
c = 3
tom = [a,b,c]
for i in tom:
i = 6
The desired result is a = 6
The actual result is a = 1
I’m guessing that there is no way to do this without some kind of exec. Correct?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Initially I misunderstood your question, and I see that kindall got it right. But I think this question shows a need for a more detailed explanation of how Python works. The best way to think about variables in Python is to think of variable names as having arrows attached to them, and values as objects to which those arrows point. Variable names point to objects. So when you do this:
You’re really saying “
apoints to1“. And when you do this:You’re really saying “
bpoints to the same object asa“. Under normal circumstances, a variable can’t point to another variable name; it can only point at the same object that the other variable points at. So when you do this:You aren’t creating a list that points to the variable names
a,b, andc; you’re creating a list that points to the same objects asa,b, andc. If you change whereapoints, it has no effect on wheretom[0]points. If you change wheretom[0]points, it has no effect on whereapoints.Now, as others have pointed out, you can programmatically alter the values of variable names, ether using
execas you suggested (not recommended), or by alteringglobals()(also not recommended). But most of the time, it’s just not worth it.If you really want to do this, my suggestion would be either simply to use a dictionary (as suggested by DzinX) or, for a solution that’s closer to the spirit of your question, and still reasonably clean, you could simply use a mutable object. Then you could use
getattrandsetattrto programmatically alter the attributes of that object like so:Generally, the best solution is to just use a dictionary. But occasionally situations might arise in which the above is better.