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? 
            Asked
            
        
        
            Active
            
        
            Viewed 227 times
        
    0
            
            
         
    
    
        Dreamer12
        
- 28
- 6
- 
                    `a,b,c,d = *list` – rdas May 05 '20 at 15:36
- 
                    1Does this answer your question? [How do I create a variable number of variables?](https://stackoverflow.com/questions/1373164/how-do-i-create-a-variable-number-of-variables) – G. Anderson May 05 '20 at 15:37
- 
                    What do you mean by "dynamic variable"? Do you mean the _name_ of the variable isn't known beforehand? – John Gordon May 05 '20 at 15:41
- 
                    @John Gordon yes something like that – Dreamer12 May 05 '20 at 15:41
- 
                    Why do you need dynamic variables? Could you use a `dict` or `list`? – luther May 05 '20 at 15:46
1 Answers
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