# create numpy arrays or lists with customiza names

Hi experts!

Im running a script with a for-cycle. In every loop a list (or np array) is generated. I wanna these lists receive the name "list_number_###", where ### is the index of the for-cycle (e.g.: if the for-cycle is " for srange(a,b+1,1)..." i wanna that the np array or list receive the names "list_number_a", "list_number_a+1",..., "list_number_b".

How can i do that?

Thanks a lot!

edit retag close merge delete

Sort by » oldest newest most voted

Have you considered using lists of lists?

list_of_np = []
for i in range(10):
list[i] = my_np_array()


or even, using list comprehensions,

list_of_np = [my_np_array() for i in range(10)]


If you are really determined to have dynamically generated variable names, Python allows you to modify the current module scope via the globals() call. You can do

for i in range(10):
globals()["list_number_" + str(i)] = my_np_array()


However in my opinion you'd better stick with one of the two previous forms.

more

As explained by @Luca, it is not a good idea to have indices as a substring of the name of your lists, but as indices: list_number[i] makes more sense than list_number_i.

Lists indices go from 0 to length-1, so if a is big (or if the set of indices is sparse), you can use a dictionary instead. For example, assume that the i^th element (more precisely the element whose key is i) of your dictionary is the list [i,i^2], you can write:

sage: a = 10
sage: b = 20

sage: dict_number = {}
sage: for i in srange(a, b+1, 1):
....:     dict_number[i] = [i, i^2]


Then you can call the element of your dictionary whose key is 13:

sage: dict_number
[13, 169]


Note that the keys of your dictionary can be more than just numbers, for example they can be strings:

sage: dict_number['plop'] = [12,13]
sage: dict_number['plop']
[12, 13]


more