Reputation:
I know this is likely a bad idea.. but seems the "best" way to do this outside of creating all possible options and ignore the unused results. I have a source file that contains values from 12 potential values.
I have all the required strings within a list already however I'm aiming to make each string the start of an list itself if this makes any sense?
For example the current list contains "a,b,c,d,e" the required output in the loop would be 'a=[].. b=[]' etc.
Upvotes: 2
Views: 96
Reputation: 402493
I do not recommend polluting your namespace by dynamically generating variables. This could especially get out of hand with large lists. You should just use a dictionary instead.
In [941]: d = {x : [] for x in 'abcde'}; d
Out[941]: {'a': [], 'b': [], 'c': [], 'd': [], 'e': []}
Look how easy this is to create and maintain.
Upvotes: 3
Reputation: 131590
Assuming you mean not "the start of a list", but "the name of a list" (as your code would suggest)... yes, this is a bad idea. You should probably use a dict
instead, something like
d = {var_name: [] for var_name in current_list}
Actually this is kind of what Python does behind the scenes. When you write
a = []
then Python is adding an entry a: []
to (something basically equivalent to) a dict
. You can see what's in that dictionary using the globals()
function if at module scope, or locals()
if inside a function.
Upvotes: 5