listpython

Checking to see if a list of lists has equal sized lists


I need to validate if my list of lists has equally sized lists.

I could write a loop to iterate over the list and check the size of each sub-list. Is there a more pythonic way to achieve the result?


Solution

  • all(len(i) == len(myList[0]) for i in myList)
    

    To avoid incurring the overhead of len(myList[0]) for each item, you can store it in a variable

    len_first = len(myList[0]) if myList else None
    all(len(i) == len_first for i in myList)
    

    If you also want to be able to see why they aren't all equal

    from itertools import groupby
    groupby(sorted(myList, key=len), key=len)
    

    Will group the lists by the lengths so you can easily see the odd one out