Better way to check if all lists in a list are the same length?
You can use a set comprehension in order to preserve the unique lengths, then check if you only have one item in set:
if len({len(i) for i in lists}) == 1:
# do stuff
Or as a more efficient way you could use a generator expression within any
or all
.
def check_size_eq(lst):
# returns true if there's any list with unequal length to the first one
return not any(len(lst[0])!= len(i) for i in lst)
# or you could do:
# return all(len(lst[0])== len(i) for i in lst)
demo :
>>> a = {1}
>>>
>>> a.pop() and not a
True
>>> a = {1,3}
>>> a.pop() and not a
False
First of all, your solution is not O(logn). And there can't be a logarithmic algorithm. You'll have to check each item at least once, so O(n) is the optimal complexity.
# import imap from itertools on Py2
if len(set(map(len, lists))) not in (0, 1):
raise ValueErrorr('not all lists have same length!')
I'd do it with a generator expression and all
:
it = iter(lists)
the_len = len(next(it))
if not all(len(l) == the_len for l in it):
raise ValueError('not all lists have same length!')
This avoids checking the length of the first list twice and does not build throwaway list/set datastructures.
all
also evaluates lazily, which means it will stop and return False
as soon as the first list which differs in length is yielded by the generator.