1

My users will be creating an arbitrary number of Human objects and grouping them in as many groups as they like. (The number of groups created will be tracked) I want to create a list for each group that they've created to use later. How can I create a list for each group if I don't know how many groups there will be?

I've thought of something like the following:

for i in range(num_groups):
    eval('group_' + str(i) + ' = []')

which should create an empty list for group i named group_i. I've read that eval is not something that should be used in most cases, so I'm wondering if there's a better way.

JerAnsel
  • 13
  • 4

2 Answers2

1

Have you thought about

groups = [[] for i in range(num_groups)]

instead of

for i in range(num_groups):
    eval('group_' + str(i) + ' = []')

That way you declare num_groups lists.

Captain Trojan
  • 2,800
  • 1
  • 11
  • 28
0

You could use a dictionary of lists, so that each name in the form of "group_i" will hold a new list inside that dictionary ("group_i" being the key). If you want to get all lists, you can just have all keys and find corresponding values to reach particular list.

Decleration will be as the following

all_groups = {}
for i in range(num_groups):
    new_group_name = "group_" + str(i)
    all_groups[new_group_name] = []

In order to add item to a particular group

all_groups[group_name].append(item)

And you can reach all group names by reaching all keys of dictionary

all_groups.keys()
gsan
  • 549
  • 1
  • 4
  • 14