Say I want to iterate over a list and create a new variable at each iteration.
Creating a new list and using append()
is not always the most convenient output, as it might be easier to directly access each new variable.
A possible solution might be using globals(). For example:
for i,n in enumerate(["Amy", "Luis", "Jerry"]):
globals()["person_" + str(i)] = "my name is " + n
The output:
person_0
'my name is Amy'
person_1
'my name is Luis'
person_2
'my name is Jerry'
This seems like a very simple solution. However, I have seen advices against using globals()
, but I couldn't find a proper explanation.
What is the reason for this? What might be a different solution which doesn't involve using list append?