I want a function check
to check that a given list
reduces ("boils down") to exactly one value under a given function reduce_function
. (A common example could be to check that a list of lists contains sublists of equal length only.)
I see at least the three following ways to achieve this. For each of them, I see some advantages and disadvantages. None of them really looks very readable to my eye. Could you give me an elaborate overview about:
Which one would be considered most readable and most "pythonic"?
1. Measure the length of the set of reduced values.
This seems most readable, but requires reduce_function
to return a hashable:
def check(lst):
return len(set(map(reduce_function, lst))) == 1
2. Count the number of groups
def check(lst):
return len(list(itertools.groupby(lst, key=reduce_function)) == 1
3. Use all
on comparison with first element
This needs an additional or
-statement (which could be replaced by an if
-else
-statement) to cover the case of lst
being empty.
def check(lst):
return not lst or all([reduce_function(el) == reduce_function(lst[0]) for el in lst])