1

I have 3 arrays that is already defined:

array1[:,:,:]
array2[:,:,:]
array3[:,:,:]

In Unix I would do the following:

for ((i=1;i<4;i++))
do 
a = array$i[:,:,:]*1000
echo a 
done

This would give:

array1[:,:,:]
array2[:,:,:]
array3[:,:,:]

How can I do this in Python in a for loop?

2 Answers 2

3

the completely legit nice way? put the 3 arrays in a list and iterate through that list.

a1 = [1, 2, 3]
a2 = [4, 5]
a3 = [6]

array_list = [a1, a2, a3]

for a in array_list:
    print(a)

Output:

[1, 2, 3]
[4, 5]
[6]

That is the ideal way to do it, you should not ideally be fiddling with names. However, is it possible if you want to using globals.

a1 = [1, 2, 3]
a2 = [4, 5]
a3 = [6]

for i in range(1, 4): #range is right exclusive
    print(globals()['a' + str(i)])

Output:

[1, 2, 3]
[4, 5]
[6]

However, just because it is possible does not mean it is recommended.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks.. it helped :)
0

To do this in python it makes more sense to use a dict like so (and I'm ignoring that [:,:,:] is a syntax error):

arrays = {}
arrays[1] = [:,:,:]
arrays[2] = [:,:,:]
arrays[3] = [:,:,:]

for i in arrays:
    a = arrays[i] * 1000
    print(a)

1 Comment

array1[:,:,:] is a valid syntax for numpy arrays.

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.