1

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 group_name

group_name will be: group1

Now I want to make an empty list called group1. How to do such a thing?

Amzraptor
  • 161
  • 3
  • 11
  • Why do you want to do this? General advice would be: Don't do this. – Steve Apr 18 '13 at 20:23
  • Why you want to do such a thing? – aldeb Apr 18 '13 at 20:23
  • Could you give more details about what you're trying to do (the big picture)? It's possible to do literally what you're asking, but I find it unlikely that this is really what you want. – ezod Apr 18 '13 at 20:24
  • related: http://stackoverflow.com/questions/14241133/how-can-i-create-lists-from-a-list-of-strings/ – Jon Clements Apr 18 '13 at 20:24
  • There was absolutely no way I could avoid this. These shelf groups will be constructed depending on how far the player "has traveled" which is unknown before the program runs – Amzraptor Apr 18 '13 at 21:59

3 Answers3

5

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!")
mgilson
  • 300,191
  • 65
  • 633
  • 696
2

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

#making shelfs
groups = {}
group_number = 1
name = str(group_number)
groups[name] = [] # or whatever
print groups[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.

John La Rooy
  • 295,403
  • 53
  • 369
  • 502
1

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

vlad-ardelean
  • 7,480
  • 15
  • 80
  • 124