Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

list

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

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

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

like image 273
Fırat Uyulur Avatar asked Mar 13 '17 19:03

Fırat Uyulur


2 Answers

Programmatically making variables is a very bad idea. Make a dictionary instead with those names as keys:

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

Then you can append to them like this:

my_lists['a'].append(some_data)

This also gives you the advantage of easily being able to loop through them if you need to.

like image 146
Novel Avatar answered Oct 02 '22 01:10

Novel


Here you go, it uses the function exec to execute the command as if it were typed by you but you use i as a dynamic variable name

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

Keep in mind this isn't very safe to do

like image 22
Andria Avatar answered Oct 02 '22 02:10

Andria