Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding the minimum length of multiple lists

Tags:

python

list

min

I have three lists of different lengths.

For example

List1 is of length 40
List2 is of length 42
List3 is of length 47

How can I use the Python inbuilt min() or any other method to find the list with the minimum length?

I tried:

 min(len([List1,List2,List3]))

but I get TypeError: 'int' object is not iterable

like image 996
user3397243 Avatar asked Dec 05 '22 03:12

user3397243


2 Answers

You need to apply len() to each list separately:

shortest_length = min(len(List1), len(List2), len(List3))

If you already have a sequence of the lists, you could use the map() function or a generator expression:

list_of_lists = [List1, List2, List3]
shortest_length = min(map(len, list_of_lists))  # map function
shortest_length = min(len(l) for l in list_of_lists)  # generator expr

To find the shortest list, not the shortest length, use the key argument:

list_of_lists = [List1, List2, List3]
shortest_list = min(list_of_lists, key=len)
like image 55
Martijn Pieters Avatar answered Dec 17 '22 08:12

Martijn Pieters


Use generator expression

min(len(i) for i in [List1,List2,List3])
like image 44
Avinash Raj Avatar answered Dec 17 '22 07:12

Avinash Raj