0

I want to create a 2D array of functions. The method I used worked for 1D array of functions, however it doesn't work for 2D array of functions.

import numpy as np
r=2
c=2

f1D=  [None]*r
f2D= [ [None] * c ] * r

def f1():
    return 1
def f2():
    return 2

f1D[0]=f1
f1D[1]=f2

f2D[0][0]=f1
f2D[0][1]=f1
f2D[1][0]=f2
f2D[1][1]=f2

print('f1D')
for i in np.arange(r):
    print(f1D[i]())

print('f2D')
for i in np.arange(r):
    for j in np.arange(c):
        print(f2D[i][j]())

The output is:

f1D
1
2
f2D
2
2
2
2

Clearly incorrect for what I want on f2D.

Vitor Abella
  • 1,213
  • 8
  • 15
  • Not sure why you'd want to do this in the first place, but the way you construct your `f2D= [ [None] * c ] * r` means you're just getting two references to the same list, not two similar copies like you seem to expect – Grismar Jun 09 '20 at 01:09
  • Duplicated suggestion worked – Vitor Abella Jun 09 '20 at 01:13

0 Answers0