简体   繁体   中英

How to create a list with objects in python

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']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM