I have a multiple 2D arrays with name temp1, temp2, temp3... etc
temp1 = [[7, 2, 4],
[5, 0, 6],
[8, 3, 1]]
temp2 = [[1, 1, 1],
[1, 1, 1],
[1, 1, 1]]
temp3 = [[2, 2, 2],
[2, 2, 2],
[2, 2, 2]]
I want to run a for loop that will return only some of the arrays depending on the range of i. I am thinking of something like
for i in range(1,3):
arrayName = ("temp" + str(i))
print(arrayName)
where print(arrayName) prints out the actual array instead of a string
Any help is appreciated!
3 Answers 3
You could do this with exec(). Also your range() should have an upper bound of your max value plus one. The upper bound is not inclusive.
for i in range(1, 4):
exec(f'print(temp{str(i)})')
Output:
[[7, 2, 4], [5, 0, 6], [8, 3, 1]]
[[1, 1, 1], [1, 1, 1], [1, 1, 1]]
[[2, 2, 2], [2, 2, 2], [2, 2, 2]]
Comments
You can use eval(). It allows you to get a variable by name.
for i in range(1, 4):
current_array = eval(f'temp{i}')
print(current_array)
But, I advise you to set this part of code to the try/except block because you can have NameError exception. And your code will look like:
for i in range(1, 4):
variable_name = f"temp{i}"
try:
current_array = eval(variable_name)
print(current_array)
except NameError:
print(f"Can not get variable with {variable_name} name")
Comments
I notice that this is your requirement:
... where print(arrayName) prints out the actual array instead of a string
If so, you could use the following simplified design pattern:
arrays = [array1, array2, array3]
for array in arrays:
print(array)
And, in modification of your code, so that print() will 'print out the actual array instead of a string':
temp1 = [[7, 2, 4],
[5, 0, 6],
[8, 3, 1]]
temp2 = [[1, 1, 1],
[1, 1, 1],
[1, 1, 1]]
temp3 = [[2, 2, 2],
[2, 2, 2],
[2, 2, 2]]
temps = [temp1, temp2, temp3]
for i in temps:
print(i)
Some further thoughts:
I would avoid the eval() or exec() Python methods as suggested by the other commenters. Simpler solutions are possible; you do not have a concrete reason to use dynamic execution.
There is a cleaner way to refactor your code, but I am providing the above answer that mirrors your code structure more directly so as to avoid confusion.
Comments
Explore related questions
See similar questions with these tags.