Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have a number of lists that I'm going to use in my program, but I need to be sure that they are all the same length, or I'm going to get problems later on in my code.

What's the best way to do this in Python?

For example, if I have three lists:

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

I could do something like:

l = [len(a), len(b), len(c)]
if max(l) == min(l):
   # They're the same

Is there a better or more Pythonic way to do this?

like image 900
robintw Avatar asked Feb 08 '12 20:02

robintw


People also ask

How do you check if all values in 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.

How do you check if two lists are the same length in Python?

If there is only one value, then they are of the same length. if len(set(map(len,lists)))==1: print("All are the same length") else: print("They are not the same length!")

How do you check if all elements in a list are the same length Python?

Using Count() The python list method count() returns count of how many times an element occurs in list. So if we have the same element repeated in the list then the length of the list using len() will be same as the number of times the element is present in the list using the count().

How do you compare lists of different lengths in Python?

Short answer: The most Pythonic way to check if two ordered lists l1 and l2 are identical, is to use the l1 == l2 operator for element-wise comparison. If all elements are equal and the length of the lists are the same, the return value is True .


2 Answers

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.

like image 188
Sven Marnach Avatar answered Sep 23 '22 10:09

Sven Marnach


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.

like image 44
Dan D. Avatar answered Sep 21 '22 10:09

Dan D.