Compare the length of three lists in python

Is there a better way to compare the length of three lists to make sure they are the same size, except for comparisons between each set of variables? What if I wanted to check the length is equal to ten lists. How can I do it?

+6
source share
3 answers

Using all() :

 length = len(list1) if all(len(lst) == length for lst in [list2, list3, list4, list5, list6]): # all lists are the same length 

Or find out if any of the lists has a different length:

 length = len(list1) if any(len(lst) != length for lst in [list2, list3, list4, list5, list6]): # at least one list has a different length 

Note that all() and any() will be short-circuited, so if, if list2 is of different lengths, it will not perform a comparison for list3 via list6 .

If your lists are stored in a list or tuple instead of separate variables:

 length = len(lists[0]) if all(len(lst) == length for lst in lists[1:]): # all lists are the same length 
+14
source

Assuming your lists are stored in a list (called my_lists ), use something like this:

 print len(set(map(len, my_lists))) <= 1 

This calculates the lengths of all the lists that you have in my_lists , and puts those lengths into a set. If they are all the same, the set will contain one element (or zero, you have no lists ).

+3
source

One liner using itertools.combinations()

 import itertools l1 = [3,4,5] l2 = [4,5,7] l3 = [5,6,7,8,3] L = [l1, l2, l3] verdict = all([len(a)==len(b) for a,b in list(itertools.combinations(L,2))]) 

First, compile a list of the list, L Then query all sets of two elements from L using list(itertools.combinations(L,2)) :

 >>> list(itertools.combinations(L,2)) [([3, 4, 5], [4, 5, 7]), ([3, 4, 5], [5, 6, 7, 8, 3]), ([4, 5, 7], [5, 6, 7, 8, 3])] 

Then check the lengths for each pair in this list. Finally, take the intersection of booleans, with all() .

 >>> verdict False 

It is right. Try using lists of attempts of the same size.

 l1 = [3,4,5] l2 = [4,5,7] l3 = [5,6,7] L = [l1, l2, l3] verdict=all([len(a)==len(b) for a,b in list(itertools.combinations(L,2))]) 

we get

 >>> verdict True 
+1
source

Source: https://habr.com/ru/post/945708/


All Articles