-2

I am looking for a way for a for loop to be able to iterate through a list of variables and be able to use them as variables like this:

>>> a = "original"
>>> b = "original"
>>> c = "original"
>>> d = "original"
>>> for i in [a,b,c,d]:
        i = "change"
>>> print(a,b,c,d)
change change change change
user36456453765745
  • 129
  • 1
  • 2
  • 6
  • The answer is `exec` if that's actually necessary, but it's highly likely that you don't need that. Why do you want to do this? – zondo Apr 06 '17 at 00:25
  • Not going to happen. `[a,b,c,d]` is equal to `["original","original","original","original"]`. It has no memory of the variables `a`, `b`, `c`, and `d`. Why do you want to do this, anyways? This smells like an [XY problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). – John Kugelman Apr 06 '17 at 00:25
  • I think you should probably elaborate on _why_ you want this. Given what you've shown so far, I'm tempted to say that it is impossible in python since strings are immutable and python objects are unaware of what names they are bound to ... – mgilson Apr 06 '17 at 00:25
  • Why are you not using a list, instead of individual variables? This smells like poor design. You *could* do it with object **id**s, but that's usually a *bad* idea. – Prune Apr 06 '17 at 00:25
  • 1
    I don't know what you're trying to do, but it's wrong, and you have an [XY Problem](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). – TigerhawkT3 Apr 06 '17 at 00:26

2 Answers2

1

Your initial code does not work because setting the value of "i" does not actually set the value of variables "a", "b", etc.

a = "original"
b = "original"
c = "original"
d = "original"
list = [a,b,c,d]
for i in range(0,len(list)):
    list[i] = "change"
print(list)
dimab0
  • 1,062
  • 8
  • 10
0

As the comments on the original question point out, this smells a bit and you may want to consider a different way of solving the actual problem. That being said, here's how you might accomplish what you're trying to do:

a = "original"
b = "original"
c = "original"
d = "original"
l = [a, b, c, d]

for idx, val in enumerate(l):
    l[idx] = "change"

print(l)

This results in:

['change', 'change']

Note that print(a) still will result in original as Python strings are immutable

Community
  • 1
  • 1
Rob Gwynn-Jones
  • 677
  • 1
  • 4
  • 14