# list building - consecutive

Hi experts!

How can i create N empty NUmpy arrays or lists (L1, L2, L3, ..., LN) in a 'for' cycle, i.e.:

for j in srange(N):
Lj=np.empty(A)


(A= numbers of element in the array).

Thanks a lot.

edit retag close merge delete

Sort by ยป oldest newest most voted
sage: [np.empty(A) for j in range(N)]

more

Maybe i didnt express me right...

In my script i wanna write a 'for' cycle that create N arrays separated, named L1, L2, ..., LN.

I mean: how can i introduce this successives numbers (1,2,...,N) in the array (or list) names whis that cycle?

Thanks a lot.

more

Actually, the answer of @volker-braun was quite satisfactory, since it creates a list that you can call:

# data you should add in your question to ease reproduction:
sage: import numpy as np
sage: N = 4
sage: A = 3

sage: L = [np.empty(A) for j in range(N)]
sage: L[0]
array([  6.89920558e-310,   6.89920558e-310,   0.00000000e+000])
sage: L[3]
array([  6.89920558e-310,   6.89920558e-310,   0.00000000e+000])


But you should notice that elements of a list L are numbered from 0 to len(L)-1.

Perhaps are you looking for a dictionary:

sage: L = dict()
sage: for j in srange(1, N+1):
sage:     L[j]=np.empty(A)
sage: L
{1: array([  6.89920558e-310,   5.92371271e-316,   5.43231038e-310]),
2: array([  6.89920558e-310,   5.91607169e-316,   5.40520702e-316]),
3: array([  6.89920558e-310,   5.91582347e-316,   5.43231038e-310]),
4: array([  6.89920558e-310,   5.91594758e-316,   1.09178468e-316])}
sage: L[1]
array([  6.89920558e-310,   5.92371271e-316,   5.43231038e-310])
sage: L[4]
array([  6.89920558e-310,   5.91594758e-316,   1.09178468e-316])

more

Hello mresimulator,

I do not know, why you want to encode the index j in the name,
but you could use 'exec()' for this:

import numpy as np
N = 4
A = 3
for j in srange(N):
exec('L'+str(j)+"=np.empty(A)")


Then L1 to L4 gets defined:

>>> L1
array([  9.79748720e-251,   2.90930926e-252,   2.34745402e-251])

more

It seems that the question is about generating new global variables in code. The correct way to do that is to add them to the globals() dictionary (has nothing to do with numpy)

sage: import numpy
sage: for i in range(1, 5):
....:     variable_name = 'L'+str(i)
....:     globals()[variable_name] = numpy.empty(3)
sage: L1
array([  1.26596386e-312,   1.26596386e-312,   6.90349880e-310])

more