0

I couldn't find a guide that would help me out in this area. So I was hoping somebody could help me explain this kind of programming in Python. I am trying to write a code that goes something like this:

def Runner():
    for G in range(someRange):
        makeListObjectcalled 'ListNumber'+'G'
        ListNumberg.append(G*500000 or whatever)
        print ListNumberG 
    #so I would have a someRange amount of lists 
    #named 0,1,2,3...(up to someRange) I could look through

I think it can be done with classes (in fact I'm guessing thats what they're for...) but I'm not sure. Could someone lay me down some clarifications please?

1
  • The most important question is why do you think you need to do it this way, and what do the names mean? For that reason, giving more context might help. Either of wez's answer or Eric Finn's answer might be right, depending on that. If the names are meaningful, use the dictionary. If you just need a bunch of different lists, (or lists in a particular order), use the list of lists solution Eric gave. Commented Jun 5, 2012 at 15:58

2 Answers 2

1

It looks like what you really want is a list of lists.

def Runner():
    Lists = []
    for G in range(someRange):
        Lists[G] = []
        Lists[G].append(G*500000 or whatever)
        print Lists[G]
        #This way, you have Lists[0], Lists[1], ..., Lists[someRange]
Sign up to request clarification or add additional context in comments.

1 Comment

Indeed! I couldn't exactly point my finger on how to summarize it in one simple step. Thank you loads!
1

You want to dynamically create variables of type lists that store an array of values.

An easier and better approach (than juggling unknown variable names) is to use a dictionary to keep your lists in, so you can look them up by name/key:

(pseudo code, don't have my Python interpreter with me)

# create a dictionary to store your ListNumberG's
dict_of_lists = {}

# down the line in your loop, add each generated list to the dict:
dict_of_lists['ListNumberG'] = ListNumberG

Later you can find a list by it's name/key via

print(dict_of_lists['ListNumberG'])

or loop through them

for idx in range(bestguess):
    print(dict_of_lists['ListNumber%s' % (idx,)])

1 Comment

This actually helped me on another problem I was working on, thank you big time Wez. You've just made my day immensely productive ^.^

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.