Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Better way to check if all lists in a list are the same length? [duplicate]

Currently running with:

l1 = [i for i in range(0,10)]
l2 = [i for i in range(0,10)]
l3 = [i for i in range(0,10)]
lists = [l1, l2, l3]
length = len(lists[0])
for l in lists:
    if length != len(l):
        raise ValueErrorr('not all lists have same length!')

Is there a prettier way to test for this than a for loop? Is there a faster/better way which isn't O(n) ?

like image 208
deepbrook Avatar asked Mar 04 '16 08:03

deepbrook


2 Answers

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.

like image 67
timgeb Avatar answered Oct 04 '22 01:10

timgeb


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
like image 28
Mazdak Avatar answered Oct 04 '22 01:10

Mazdak