list_name = "a"
list_element = "b"
I want to create a list in below format
a = ["b"]
How cani achieve this with format of list_name
and list_element
?
Thank you!
list_name = "a"
list_element = "b"
I want to create a list in below format
a = ["b"]
How cani achieve this with format of list_name
and list_element
?
Thank you!
You can do this easily using globals()
:
globals()[list_name] = [list_element]
out put:
In [1]: list_name = "a"
In [2]: list_element = "b"
In [3]: globals()[list_name] = [list_element]
In [4]: a
Out[4]: ['b']
Read more about globals().
What you are trying to do here is to create variable names dynamically. Except if you really really need to do it, it is not recommended and can usually be avoided.
In Python, dictionaries can be used to solve this problem. A dictionary contains variables which can be called using "keys".
dict = {'a1' : "b1",
'a2' : "b2"}
The variable (here the string "b1") associated with the key 'a1' can be called using:
dict['a1']