Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

list

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.

like image 888
nitin Avatar asked May 30 '12 22:05

nitin


People also ask

How do you know if two lists are equal?

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.

How do you check if all the elements of a list 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.

Can you use == for lists in Python?

Python sort() method and == operator to compare lists Further, the == operator is used to compare the list, element by element.


2 Answers

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

like image 97
John La Rooy Avatar answered Oct 12 '22 00:10

John La Rooy


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

like image 24
Santiago Alessandri Avatar answered Oct 12 '22 01:10

Santiago Alessandri