3

How can a generate multiple array with this syntax result0, result1, result2 etc..

I tried this and this work :

for i in xrange(0, 7):
        var_num = i
        globals()['result%s' % var_num] = []
        globals()['result%s' % var_num].append(1000+i)
        print ['result%s' % var_num][0]

it gives me theses array :

result0
result1
result2
result3
result4
result5
result6

But i'm sure there is another way to do that?...

Thanks

3
  • 2
    The right answer is "don't". What's your real use case? Something like a defaultdict of lists might be more appropriate. (Also: Python lists are not arrays -- there are libraries offering arrays for Python, but these aren't them -- but that's a separate discussion). Commented Dec 23, 2013 at 15:52
  • 1
    nedbatchelder.com/blog/201112/… Commented Dec 23, 2013 at 15:58
  • It's generally not considered a good practice, in any language that supports it. For some reasons see Why you don't want to create dynamic variables and Never use dynamic variable names. Commented Dec 23, 2013 at 16:13

2 Answers 2

4

How about using a dictionary.

>>> variables = {}
>>> for i in xrange(0, 7):
...     variables['result%s' % i] = [1000 + i]
...
>>> variables
{'result6': [1006], 'result4': [1004], 'result5': [1005], 'result2': [1002], 'result3': [1003], 'result0': [1000], 'result1': [1001]}
>>> variables['result2']
[1002]
>>> variables['result6']
[1006]
Sign up to request clarification or add additional context in comments.

Comments

1

Why do you want to have like that? Why not just an array of arrays? You will be able to iterate over the arrays easily when you keep them in another array.

Comments

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.