What is the purpose of this append command! - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: What is the purpose of this append command! (/thread-26309.html) |
What is the purpose of this append command! - Captain_farrell - Apr-27-2020 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. RE: What is the purpose of this append command! - Yoriz - Apr-27-2020 result.append(x(i)) result is a listresult.append() append an item to the listx() x is a function passed to my_calculation and the () calls the functioni is the value obtained from iterating through the list y that is passed to my_calculation
RE: What is the purpose of this append command! - Shahmadhur13 - Apr-29-2020 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. RE: What is the purpose of this append command! - buran - Apr-29-2020 (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 * numbersame for my_calculation. First param is a function, second is sequence of numbers. e.g. def my_calculation(func, numbers): RE: What is the purpose of this append command! - bowlofred - Apr-29-2020 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.
|