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?
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
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With