Aug-09-2020, 05:13 PM
Is what you really want to do to write a generic function where the thing that varies is a function that's called inside? If so, look into the idea of higher order functions - in Python, functions are values and can be passed around like other things. A higher order function is one that takes another function as a parameter (or returns one, but the former case sounds more useful for you right now). An example of such a thing is the built in
map
function:>>> xs = [1, 2, 3] >>> list(map(lambda x: x * 2, xs)) [2, 4, 6] >>> words = ["foo", "bar", "baz"] >>> list(map(lambda w: w.upper(), words)) ['FOO', 'BAR', 'BAZ']
map
takes a function as its first argument and applies it to each item of the iterable passed as its second argument. In the two examples, I pass in two different functions: one that doubles the argument that I use with the list of ints and one that turns its argument to uppercase, which I use with the list of strings.