user1594369
user1594369

Reputation: 127

Python: Splitting lists into multiple lists

In python, Suppose I have a list:

instruments = ['apd', 'dd', 'dow', 'ecl']

How can I split these lists so that it will create:

apd[]
dd[]
dow[]
ecl[]

Thanks for the help.

Upvotes: 0

Views: 247

Answers (2)

AI Generated Response
AI Generated Response

Reputation: 8837

You would do this:

dictionaries = {i:[] for i in instruments}

and you you would refer to each list this way:

dictionaries['apd']
dictionaries['dd']
dictionaries['dow']
dictionaries['ecl']

This is considered much better practice than actually having the lists in the current namespace, as it would both be polluting and unpythonic.

mshsayem has the method to place the lists in the current scope, but the question is, what benefits do you get from putting them in your current scope?

Standard use cases:

  • you already know the names of the items, and want to refer to them directly by name, i.e. apd.append
  • you don't know the names yet, but you'll use eval or locals to get the lists, i.e. eval('apd').append or locals()['apd'].append

Both can be satisfied using dictionaries:

  • dictionaries['<some name can be set programatically or using a constant>'].append

Upvotes: 3

mshsayem
mshsayem

Reputation: 18008

Try this:

instruments = ['apd', 'dd', 'dow', 'ecl']
l_dict = locals()
for i in instruments:
    l_dict[i] = []

This will create apd,dd,dow,ecl lists in the local scope. Snakes and Cofee's idea is better though.

Upvotes: 1

Related Questions