1

I have a 2D matrix called A0

A0 = [[0 for x in range(3)] for y in range(3)]

I have a function called newProb which takes this as an argument and returns another 2D matrix in the following way:-

A1 = newProb(A0)

So, I want to put this code into a loop.

A1 = newProb(A0)
A2 = newProb(A1)
A3 = newProb(A2)
A4 = newProb(A3)

Any help will be appreciated. Thanks!

P.S. I have to make 100 calls to that function in the above way

Soviut
  • 88,194
  • 49
  • 192
  • 260
Nihal Rp
  • 484
  • 6
  • 15
  • Possible duplicate of [generating variable names on fly in python](http://stackoverflow.com/questions/4010840/generating-variable-names-on-fly-in-python) – Jean-François Fabre Dec 05 '16 at 22:11
  • Why not just create a list, add the result of each call to the list, then on the next iteration use the previous list value? Or you could use recursion. – SteveJ Dec 05 '16 at 22:14
  • @SteveJ . yeah i will try that. Thank you – Nihal Rp Dec 05 '16 at 22:15

6 Answers6

1

Rather than trying to create local variables in your loop, you'd be better off storing the results in a list. Your list's index will line up nicely with your naming convention.

A = []

A.append([[0 for x in range(3)] for y in range(3)])

A[1] = newProb(A[0])
A[2] = newProb(A[1])
# ...

You can then easily put this into a loop with a range.

# start the range off by 1
for i in range(1, 10):
    A[i] = newProb(A[i - 1])

This could also be written as

for i in range(10):
    A.append(newProb(A[i]))
Nihal Rp
  • 484
  • 6
  • 15
Soviut
  • 88,194
  • 49
  • 192
  • 260
0

Use a dict:

A = {}
A[0] = [[0 for x in range(3)] for y in range(3)]
for i in range(1, 101):
    A[i] = newProb(A[i-1]) 
jez
  • 14,867
  • 5
  • 37
  • 64
0

You can store your values in a list generated like so:

A = [A0]
for i in range(99):
    A.append(newProb(A[i]))
Keiwan
  • 8,031
  • 5
  • 36
  • 49
0

Combining the answers from @jez and @Soviut:

A = []
A.append([[0 for x in range(3)] for y in range(3)])

for i in range(100):
    A.append(newProb(A[-1])

A[-1] is the last element in the list.

Brad Campbell
  • 2,969
  • 2
  • 23
  • 21
0

If you just need the 'final' value, after the 100st loop:

value = [[0 for x in range(3)] for y in range(3)]
for i in range(100):
    value = newProb(value)
Maurice Meyer
  • 17,279
  • 4
  • 30
  • 47
0

Round out the answers with a while loop

A = [A0]
while len(A) < 100:
    A.append(newProb(A[-1]))
wwii
  • 23,232
  • 7
  • 37
  • 77