0

if one had a list of strings, how could they create variables (empty list objects) with those names?

pre_vars= ['list_1','list_2','list_3']

print list_1,list_2,list_3 

>>> [],[],[]

I saw some examples that were similar but they were using classes. Can this be done without using classes?

O.rka
  • 29,847
  • 68
  • 194
  • 309
  • If this was possible, what would you expect their initialized values to be? – Anthony Forloney Jan 14 '15 at 00:37
  • Just empty list objects to fill in later – O.rka Jan 14 '15 at 00:37
  • Why would you want to do this? –  Jan 14 '15 at 00:40
  • Use file directory as input, create a list for every file in the directory, add specific entries from each file into respective lists, use sets to find out the which elements overlap @LegoStormtroopr – O.rka Jan 14 '15 at 00:44
  • 1
    Better use a dict then, you won't be able to create variables with file names that are not valid Python identifiers. Plus this will mess up the namespace. – Ashwini Chaudhary Jan 14 '15 at 00:46
  • Why not use a dictionary, or a list of lists? What happens if you have a directory called 'print'? –  Jan 14 '15 at 00:46

1 Answers1

3

Use globals():

for name in pre_vars:
    globals()[name]= []
Aran-Fey
  • 39,665
  • 11
  • 104
  • 149