Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculating minimum length among the lists inside a list

Tags:

python

list

a=[[1,0,1,2,1,1,1,3111111],[31,1,4,51,1,1,1],[1,1,6,7,8]]
print min(a[0],a[1],a[2])

The following code returns the [1, 0, 1, 2, 1, 1, 1, 3111111]. Not sure what is the default key and according to what logic is it returned?

Plus I was actually trying to find the minimum length out of these lists within a list.

I wrote this min(len(a[0]),len(a[1]),len(a[2])). Can this be made any better?

like image 829
PythonEnthusiast Avatar asked Sep 11 '13 12:09

PythonEnthusiast


3 Answers

A few options:

a = [[1,0,1,2,1,1,1,3111111], [31,1,4,51,1,1,1], [1,1,6,7,8]]

print min(a, key=len)
# [1, 1, 6, 7, 8]

print len(min(a, key=len))
# 5

print min(map(len, a))
# 5
like image 131
grc Avatar answered Oct 17 '22 19:10

grc


Yes, you can use map to iterate over the inner lists to create a list of lengths, then get the minimum with min:

>>> a=[[1,0,1,2,1,1,1,3111111],[31,1,4,51,1,1,1],[1,1,6,7,8]]
>>> min(map(len, a))
 5
like image 28
jabaldonedo Avatar answered Oct 17 '22 21:10

jabaldonedo


You could write it as a loop to create a list instead of having to type it always:

min([len(x) for x in a])

This would acomplish what you want no matter how many lists are inside a

like image 43
fditz Avatar answered Oct 17 '22 20:10

fditz