0

I have a list which, lets say it looks like this:

alist = ["apple", "tea", "oranges"]

What I want python to do now is take each attribute and create an empty list out of it. So basically this:

apple = []
tea = []
oranges = []

How can I accomplish this?

four-eyes
  • 10,740
  • 29
  • 111
  • 220

2 Answers2

2

You could (but shouldn't) use exec:

for item in alist:
    exec(item + " = []")

This is, however, generally discouraged. Use a dict instead:

list_dict = {}
for item in alist:
    list_dict[item] = []
hlt
  • 6,219
  • 3
  • 23
  • 43
  • Thanks. I guess I need lists since I have more VALUES which need to go into these created lists (and the dic only has one KEY). However, with your solution `exec`. How would I append something to these created lists? Of course with `.append`, but how (since it does not give me anything as an output) – four-eyes Aug 12 '14 at 19:54
  • These lists now exist. If `alist` contained `"apple"`, then there is a list called `apple` that you can use like any other list (e.g., `apple.append(...)`) – hlt Aug 12 '14 at 19:56
1

You could do so by holding the list names as the keys of a dictionary. Something like this:

alist = ["apple", "tea", "oranges"]
yourListDict = {}
for name in alist:
    yourListDict[name]=list() 

Output:

yourListDict['apple']
=> []

An alternative syntax would be:

{k: [] for k in alist}

as Jon Clements points out in: https://stackoverflow.com/a/14241195/2259303

Community
  • 1
  • 1
agconti
  • 17,780
  • 15
  • 80
  • 114
  • I support the `dict` recommendation, but that's not valid Python syntax. – DSM Aug 12 '14 at 19:45
  • @DSM just realized. updated. thanks! – agconti Aug 12 '14 at 19:45
  • Thanks. But I think I need lists since I will `.append` more than one value to the so created list. That would end in trouble with the dic when I try to assign more than one VALUE to the same KEY – four-eyes Aug 12 '14 at 19:56
  • @Christoph the values *are* lists. you could do `yourListDict['apple'].append("myString")`. then if you printed `yourListDict['apple']` you'd get `["myString"]`. It would work just like a list! the only thing different is how you access it. – agconti Aug 12 '14 at 20:03