How to Compare the Length of Multiple Lists in Python?

Estimated read time 2 min read

To compare the lengths of multiple lists in Python, you can use the len() function to retrieve the length of each list and then compare them using comparison operators. Here’s an example:

# Define your lists
list1 = [1, 2, 3]
list2 = ['a', 'b', 'c', 'd']
list3 = [True, False, True, False, True]

# Compare the lengths
if len(list1) < len(list2) and len(list1) < len(list3):
    print("list1 is the shortest")
elif len(list2) < len(list1) and len(list2) < len(list3):
    print("list2 is the shortest")
elif len(list3) < len(list1) and len(list3) < len(list2):
    print("list3 is the shortest")
else:
    print("There are multiple lists with the same shortest length")

In this example, we have three lists, list1, list2, and list3. We use the len() function to obtain the lengths of each list. We then compare the lengths using comparison operators (<, >).

You can extend this example to compare more than three lists by adding additional elif conditions for each list. The if-elif structure allows you to compare the lengths and perform different actions based on the results.

The example provided assumes that you want to find the shortest list among the given lists. If you want to find the longest list, you can modify the conditions accordingly by using the > operator instead of <.

By comparing the lengths of multiple lists, you can determine which list is the shortest or longest based on your specific requirements.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply