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

1 Answer 1

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

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.