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?
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 .
To get the length of a list in Python, you can use the built-in len() function.
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.
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
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).
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