Finding the minimum length of multiple lists
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 built-in min()
Python min()
or any other method to find a list with the minimum length?
I tried:
min(len([List1,List2,List3]))
but i get TypeError: 'int' object is not iterable
+3
source to share
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 lists, you can use a generator function map()
or 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 argument key
:
list_of_lists = [List1, List2, List3]
shortest_list = min(list_of_lists, key=len)
+11
source to share