0

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.

2
  • Why do you want to do this? What's your use case? Commented May 28, 2013 at 5:37
  • 1
    a tonne of people ask this same question but none of them really want to do it this way, use a dictionary Commented May 28, 2013 at 5:41

2 Answers 2

3

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
Sign up to request clarification or add additional context in comments.

1 Comment

Perfect, much cleaner and easier to use a dictionary. Thank you.
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.