I need to validate if my list of list has equally sized lists in python
myList1 = [ [1,1] , [1,1]] // This should pass. It has two lists.. both of length 2
myList2 = [ [1,1,1] , [1,1,1], [1,1,1]] // This should pass, It has three lists.. all of length 3
myList3 = [ [1,1] , [1,1], [1,1]] // This should pass, It has three lists.. all of length 2
myList4 = [ [1,1,] , [1,1,1], [1,1,1]] // This should FAIL. It has three list.. one of which is different that the other
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.
equals() method. A simple solution to compare two lists of primitive types for equality is using the List. equals() method. It returns true if both lists have the same size, and all corresponding pairs of elements in both lists are equal.
You can convert the list to a set. A set cannot have duplicates. So if all the elements in the original list are identical, the set will have just one element. if len(set(input_list)) == 1: # input_list has all identical elements.
Python sort() method and == operator to compare lists Further, the == operator is used to compare the list, element by element.
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
You could try:
test = lambda x: len(set(map(len, x))) == 1
test(myList1) # True
test(myList4) # False
Basically, you get the length of each list and make a set from those lengths, if it contains a single element then each list has the same length
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With