I'm running into this problem often: I'm creating a function that needs to perform a series of operations on a value, whether that value be a single value or a list of values.
Is there an elegant way to do this:
do a series of things to each value, whether list or single val
return answer or list of answers
if isinstance(val, list):
... do a series of things to each list item,
return a list of answers
... do the same series, just on a single value
return a single answer
If the function makes sense for a single value, as well as for a list, then logically the function's result for a certain list item will not depend on the other items in the list.
b should end up identical:
items = [1, 2] a = convert_val(items) b = map(convert_val, items)
This example already hints at the solution: the caller knows whether a list or a single value is passed in. When passing a single value, the function can be used as-is. When passing a list, a
map invocation is easily added, and makes it clearer what's happening on the side of the caller.
Hence, the function you describe should not exist in the first place!