0

I have a list like this list = ["mkhg" , "ghkl" , "hjyu" , "jkkp"] I want to iterate through this list and store the values in dynamic variables. Say for example, "mkhg" is stored in variable a , "ghkl" is stored in variable c and so on. Is there a way to crack this?

Dreamer12
  • 28
  • 6

1 Answers1

1
list = ["mkhg" , "ghkl" , "hjyu" , "jkkp"]

Variable name shadows the bultin list type, don't do that.

You can achieve this with exec but it's a really dirty hack, so it's more of a fun fact rather than useful pattern:

l = ["mkhg" , "ghkl" , "hjyu" , "jkkp"]
variable_names = ["a","b","c","d"]

for name, value in zip(variable_names, l):
    exec(f"{name}=value")
print(a) # mkhg

Most times you'll be better of with a dict:

values = {"a": "mkhg", "b": "ghkl"}
# or dynamically created

values = dict(zip(variable_names, l))
RafalS
  • 5,834
  • 1
  • 20
  • 25
  • Thank you so much! A quick question - is there a way to achieve this without declaring the variable names beforehand? – Dreamer12 May 05 '20 at 15:56
  • Yeah, variable names can be generated as you like, but in the end you'll need a list of strings. – RafalS May 05 '20 at 15:57