0

I have a list with list operations, For example ["insert", "append"], For now I am doing like if list says insert then I am calling .insert.

Check below code

In [31]: list_ops = [ "insert" , "append" ]

In [32]: list1 = [ 1 , 3 , 5 ]

In [33]: if list_ops[0] == "insert" :
    ...:     list1.insert(3, 7)
    ...:

In [34]: list1
Out[34]: [1, 3, 5, 7]

In [35]: list1.list_ops[0](4, 9 )
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-35-5db0dcceeac1> in <module>
----> 1 list1.list_ops[0](4, 9 )

AttributeError: 'list' object has no attribute 'list_ops'

In [36]:

How can I choose the operation from list_ops itself instead of doing if-else matching.

Thank you.

1
  • im pretty sure you cant. Commented May 29, 2020 at 5:32

2 Answers 2

2

You can't choose an operation from list_ops, because it's a list of strings, not of operations. You need to choose the operation based on the string. For instance:

list_ops = {
    "insert": list.insert,
    "append": list.append
}

Now you can choose the operation based on the input string. Can you take it from here?

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

Comments

0

You could use exec and f-Strings if you really wanted to do it:

operation = "append"
list1 = [1, 2, 3]

exec(f"list1.{operation}(4)")
print(list1) # [1, 2, 3, 4]

But to be honest, I think it's a better idea to create an operation dictionary like Prune suggested.

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.