0

I have an array of functions and I want to call them by their index. However the following code gives me an error(TypeError: 'list' object is not callable)

kFunc = [Row(a,value, row), Col(a,value,col), Gridval(a,value, row, col), Grid(a, value), Rectangle(a, value, row, col)  ]
    k = random.randint(1,4)
    for j in range(k):
        output = kFunc[j]()

Each function returns a value. I tried replacing kFunc[j]() with kFunc[j]. I didn't get any error but all the 5 functions are getting executed.

I found a similar question here but I can't figure out an answer to my question.

I'd appreciate any help. Thanks

Shankar
  • 417
  • 1
  • 6
  • 17

1 Answers1

2

You probably made a list of the return values already, assuming that Row, Col, etc. are the functions you are talking about. You can do the following to wrap those in functions:

kFunc = [
    lambda: Row(a,value, row), 
    lambda: Col(a,value,col), 
    lambda: Gridval(a,value, row, col), 
    lambda: Grid(a, value), 
    lambda: Rectangle(a, value, row, col)
]

output = kFunc[random.randint(0,4)]()  # will only do one of the lambda-wrapped operations
user2390182
  • 72,016
  • 6
  • 67
  • 89