Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare length of three lists in python [closed]

Tags:

python

Is there a nicer way to compare the length of three lists to make sure they are all the same size besides doing comparisons between each set of variables? What if I wanted to check the length is equal on ten lists. How would I go about doing it?

like image 735
MasterGberry Avatar asked May 23 '13 18:05

MasterGberry


People also ask

How do I compare two list 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 .

How do I get the length of a list in Python 3?

To get the length of a list in Python, you can use the built-in len() function.

Can we use LEN with lists in Python?

There is a built-in function called len() for getting the total number of items in a list, tuple, arrays, dictionary, etc. The len() method takes an argument where you may provide a list and it returns the length of the given list.


2 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 to find out if any of the lists have 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 short-circuit, so for example if list2 has a different length it will not perform the comparison for list3 through 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
like image 196
Andrew Clark Avatar answered Sep 28 '22 00:09

Andrew Clark


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 you have in my_lists and puts these lengths into a set. If they are all the same, the set is going to contain one element (or zero you have no lists).

like image 36
mbatchkarov Avatar answered Sep 28 '22 02:09

mbatchkarov