0

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

1

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]]
Sign up to request clarification or add additional context in comments.

Comments

0

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

0

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:

  1. 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.

  2. 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

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.