1

Suppose I have a list called "Collection":

Collection = ['a','b','c','d']

From this list, I would like to create 4 lists:

a_list = []
b_list = []
c_list = []
d_list = []

Is there a way to do something like the followings to create the above 4 lists?

for item in Collection:
    item_list = []
Starz
  • 199
  • 1
  • 6

2 Answers2

3

Generally, it is considered a bad idea to make variable names dynamic, which is why there is no easy way to do it in Python (and other languages as well).

The closest thing you can get is by using dictionaries:

c = ['a', 'b', 'c', 'd'] 
dict_with_new_lists = {item: [] for item in c}
# Now contains: {'a': [], 'c': [], 'b': [], 'd': []}

Now to access your lists:

some_variable = 'a'
print(dict_with_new_lists[some_variable])
# etc...
Remolten
  • 2,614
  • 2
  • 25
  • 29
2

I think the best approach is define default dictionary:

from collections import defaultdict

collection_dict = defaultdict(list)

Example:

from collections import defaultdict

collection_dict = defaultdict(list)

Collection = ['a','b','c','d']
for elt in Collection:
    collection_dict[elt].append('sample')
print(collection_dict)

> defaultdict(<class 'list'>, {'d': ['sample'], 'a': ['sample'], 'c':
> ['sample'], 'b': ['sample']})
anati
  • 264
  • 2
  • 13
  • 1
    got it! thank you @anati: i want to put a check mark and thumbs up for your answer and comment, but my reputation is too low.. – Starz Apr 25 '17 at 17:03