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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With