Creating empty lists with the name of the elements of another list

Say we have a list my_list=["a","b","c"]. I want to create empty lists as

a=[] b=[] c=[]

so that I can add some elements to them according to their names.

+4
source share
2 answers

Here you use a function execto execute a command as if it were entered by you, but you use ia dynamic variable as the name

for i in my_list:
  exec(i+'=[]')

Keep in mind that this is not very safe to do.

+1
source

Creating variables programmatically is a very bad idea. Create a dictionary instead of these names as keys:

my_lists = {key:[] for key in my_list}

Then you can add the following to them:

my_lists['a'].append(some_data)

, , , .

+15

Source: https://habr.com/ru/post/1672194/


All Articles