Skip to content Skip to sidebar Skip to footer

Make A List With A Name That Is Only Known After The Program Runs

I want to make a list and call it a name which I only know after I run the program: For example: #making shelfs group_number = 1 group_name = 'group' + str(group_number) print grou

Solution 1:

Usually you just put this into a dictionary:

d = {group_name:[]}

Now you have access to your list via the dictionary. e.g.:

d['group1'].append('Hello World!')

The alternative is to modify the result of the globals() function (which is a dictionary). This is definitely bad practice and should be avoided, but I include it here as it's always nice to know more about the tool you're working with:

globals()[group_name] = []
group1.append("Hello World!")

Solution 2:

You are wanting to create a pseudo-namespace of variables starting with "group". Why not use a dict instead?

#making shelfsgroups = {}
group_number = 1
name = str(group_number)
groups[name] = [] # or whateverprintgroups[name]

This is subtly different to @mgilson's answer because I am trying to encourage you to create new namespaces for each collection of related objects.

Solution 3:

you do this:

locals()['my_variable_name'] = _whatever_you_wish_

or

globals()['my_variable_name'] = _whatever_you_wish_

or

vars()['my_variable_name'] = _whatever_you_wish_

Google to find out the differences yourself :P

Post a Comment for "Make A List With A Name That Is Only Known After The Program Runs"