2

I'm looking for a way to assign variables dynamically using loop & functions in Python. One way I can do so in R is by using eval(parse(text=text)). For example, assuming I have this code:

var <- c('First','Second','Third')

for (i in 1:length(var)){
  text <- paste0("Variable_", var[i], " <- ", i)
  eval(parse(text = text))
}

And my desired output is as follow:

> Variable_First
[1] 1
> Variable_Second
[1] 2
> Variable_Third
[1] 3

What is the equivalent way of doing such in Python?

Thanks in advance!

Agnes Lee
  • 322
  • 1
  • 12
  • Does this answer your question? [How do I create variable variables?](https://stackoverflow.com/questions/1373164/how-do-i-create-variable-variables) – G. Anderson Mar 30 '21 at 18:31
  • Would a [dictionary](https://docs.python.org/tutorial/datastructures.html#dictionaries) work for your purposes? – Timur Shtatland Mar 30 '21 at 18:38
  • @G.Anderson, thank you for the link but it's not exactly what I want, as I'm looking to create multiple variables & naming them by merging a fixed string with other multiple strings. For example, from my code, `paste0("Variable_", var[i], " <- ", i)` here combines "Variable_" with a looped object that contains multiple strings, thus creating 3 different variables with same initial pattern – Agnes Lee Mar 30 '21 at 18:44
  • @TimurShtatland if dictionary works for this case I'm all ears! As long as the outcome is the same as what are detailed on top – Agnes Lee Mar 30 '21 at 18:46

2 Answers2

2

Well, if you really want to do this you can do it in pretty much the same way with exec. Its probably not the best thing to do though...

var = ["First", "Second", "Third"]
for i, j in enumerate(var, start=1):
    exec(f"Variable_{j} = i")

Giving

>>> Variable_First
1
>>> Variable_Second
2
>>> Variable_Third
3
tomjn
  • 5,100
  • 1
  • 9
  • 24
-1

Use dictionaries to accomplish something similar: "variable" variables in a restricted namespace. For example, here a dictionary comprehension is used to assign to dictionary dct:

lst = ['First','Second','Third']
dct = {f'Variable_{s}': i for i, s in enumerate(lst)}
print(dct)
# {'Variable_First': 0, 'Variable_Second': 1, 'Variable_Third': 2}
Timur Shtatland
  • 12,024
  • 2
  • 30
  • 47
  • I think the author wants to get the variable instead of the keys in some dictionary. – Jiaxiang Oct 15 '21 at 07:30
  • @Jiaxiang That may be, but the only "solution" to get the variables is to use `exec` or `eval`, which should be avoided. See, for example, [here](https://stackoverflow.com/q/9672791/967621) and [here](https://stackoverflow.com/q/1933451/967621). Using a dictionary in the standard pythonic way to solve the problem of creating "variable variables". It is safer, more robust and more maintainable. – Timur Shtatland Oct 15 '21 at 13:54