Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding the longest and the shortest lists within a list in Python [duplicate]

Tags:

python

list

max

min

I need to print the lists which have minimum and maximum number of items in a list.

For example if I have:

total_list = [[1, 2, 3], [1, 2, 3, 4], [1, 2, 3, 4, 5]]

I need to return the lists with a minimum and maximum lengths. How can I do it?

Output could be something like:

total_list[0] and total_list[2]
like image 987
J_log Avatar asked Dec 08 '22 13:12

J_log


1 Answers

max and min function in python accepts a key argument that will find the max of an iterable based on what defined as a key. so, try this:

max(total_list, key=len)

then you can use total_list.index to find those indexes

like image 183
Mehrdad Pedramfar Avatar answered Jan 29 '23 17:01

Mehrdad Pedramfar