Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - is there a way to store an operation(+ - * /) in a list or as a variable?

The reason I ask is pure curiosity. I could see, possibly, that this might be useful if you didn't know ahead of time what operations you wanted to apply to certain variables, or to apply a different operation during a certain level in a recursive call, or perhaps it may just make certain things easier and/or neater.

Though am just speculating, it could be a really bad idea, but overall am just curious.

like image 835
Jim Jam Avatar asked May 10 '16 15:05

Jim Jam


People also ask

Can we store an operator in a variable in Python?

You can map operator symbols to those functions to retrieve the proper function, then assign it to your op variable and compute op(a, b).

What is use of and * operator in list in Python?

Python List also includes the * operator, which allows you to create a new list with the elements repeated the specified number of times.

Can you assign an operator to a variable?

The simple assignment operator ( = ) is used to assign a value to a variable. The assignment operation evaluates to the assigned value. Chaining the assignment operator is possible in order to assign a single value to multiple variables.

How do you store data in a list in Python?

Creating Lists in Python You can use the in-built list() function to convert another data type into a list. It can also create an empty list without parameters.


1 Answers

You may use operator module.

The operator module exports a set of efficient functions corresponding to the intrinsic operators of Python. For example, operator.add(x, y) is equivalent to the expression x+y. The function names are those used for special class methods; variants without leading and trailing __ are also provided for convenience.

So storing "operation" in list is as simple as:

import operator
operations = [operator.add, operator.sub]
# add two numbers
s = operations[0](1, 2)
like image 64
Łukasz Rogalski Avatar answered Sep 28 '22 08:09

Łukasz Rogalski