I want to create a list of squares of even numbers by creating a list, applying the callback functions to each element of the list and puts the result in a list. But how do I implement callback in the first place?
1 Answer
In this case I think you are looking for the map builtin. It takes a function and a list and then applies that function on the list storing each result as it goes. For example:
def square(x):
return x * x
list(map(square, [1, 2, 3, 4]))
>>> [1, 4, 9, 16]
Note that we need to cast the result of map back to a list since it returns a map object.
4 Comments
dublejin
Yes, but how does this implement callback?
ShadowRanger
@RohitMenon:
map's first argument is a callback function which it applies to each element of the input, with the output being the result of executing said callback.Klaus D.
This is not a callback, just a function use very similar to one.
(). You can use it as argument in other function and it will execute it later using(). So every function or method can be callback. For example intkinteryou can assign function name to button and button will execute this function later, when you click this button. So assigned function is called "callback".