A function can also receive another function as parameter. The following example includes the function calculuevalue which takes as parameters l and f. This function calculates for all the values x in the list l the value f (x). function_carre or function_cube are passed in parameters to the function calculuevalue which executes them.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | def function_square (x): return x * x def function_cube (x): return x * x * x def calculationnevalue (l, f): res = [f (i) for i in l] return res l = [0, 1, 2, 3] print (l) # displays [0, 1, 2, 3] l1 = calculation of value (l, function_square) print (l1) # prints [0, 1, 4, 9] l2 = calculation of value (l, function_cube) print (l2) # prints [0, 1, 8, 27] |
>>>
1 2 3 4 5 | [0, 1, 2, 3] [0, 1, 4, 9] [0, 1, 8, 27] |
The code you provided defines three functions: function_square
, function_cube
, and calculationnevalue
. The function_square
function takes in a variable x
and returns the square of that variable. The function_cube
function also takes in a variable x
and returns the cube of that variable. The calculationnevalue
function takes in a list l
and a function f
. It uses a list comprehension to apply the function f
to every element in the list l
, and assigns the result to the variable res
.
In the last part of the code, a list l
is defined as [0, 1, 2, 3]
and printed. Then, the calculationnevalue
function is used to square the elements of l
and the result is assigned to l1
, which is then printed. The same function is used again to cube the elements of l
and the result is assigned to l2
, which is then printed. The final output will be [0, 1, 4, 9] and [0, 1, 8, 27] respectively for l1 and l2.