def square(x):
return x * x
def my_calculation(x, y):
result = []
for i in y:
result.append(x(i))
return result
squares = my_calculation(square, [1, 2, 3, 4, 5])
print(squares)
sorry everyone, i am a beginner! in these codes i did not understand why we have to do ?

"result.append(x(i))
or if anyone can explain me all steps, would be much appreciated.
thanks again.
result.append(x(i))
result
is a list
result.append()
append an item to the list
x()
x is a function passed to
my_calculation
and the
()
calls the function
i
is the value obtained from iterating through the list
y
that is passed to
my_calculation
def square(x):
return x * x
def my_calculation(x, y):
result = []
for i in y:
result.append(x(i))
print(type(x))
return result
squares = my_calculation(square, [1, 2, 3, 4])
print(squares)
I als come to know that x is function by adding one extra line 9 in above code. But I am wondering there is no pre-defined function called 'x' in there. 'x' is argument in "def square(x)" only. Please enlighten.
(Apr-29-2020, 03:49 AM)Shahmadhur13 Wrote: [ -> ]But I am wondering there is no pre-defined function called 'x' in there. 'x' is argument in "def square(x)" only.
well, there is x parameter in
def my_calculation(x, y):
too.
By the way, more meaningful names would be better and make easier to follow the code.
e.g. sqare takes a number as argument.
So it would be better to write it like this
def square(number):
return number * number
same for my_calculation. First param is a function, second is sequence of numbers. e.g.
def my_calculation(func, numbers):
In the function my_calculation
, x is the first parameter that is passed in. In your program, this is called at line 13. There, the first parameter is square
, which is indeed a function defined earlier in your program.