Pythonic way to check that the lengths of lots of lists are the same

len(set(len(x) for x in l)) <= 1

Latter I ended up writing:

def some(x):
    """Replacement for len(set(x)) > 1"""

    if isinstance(x, (set, frozenset)):
       return len(x) > 1

    s = set()
    for e in x:
        s.add(e)
        if len(s) > 1:
            return True
    return False

def lone(x):
    """Replacement for len(set(x)) <= 1"""
    return not some(x)

Which allows the above to be written as:

lone(len(x) for x in l)

This will stop taking the lengths of the lists as soon as it finds a list with a different length.


Assuming you have a non-empty list of lists, e.g.

my_list = [[1, 2, 3], ['a', 'b'], [5, 6, 7]]

you could use

n = len(my_list[0])
if all(len(x) == n for x in my_list):
    # whatever

This will short-circuit, so it will stop checking when the first list with a wrong length is encountered.