I want to find the smallest value in a list of lists in Python. Example:
ls = [[2,3,5],[8,1,10]]
The minimum value in ls
is 1
. How can I get that in a simple way?
I want to find the smallest value in a list of lists in Python. Example:
ls = [[2,3,5],[8,1,10]]
The minimum value in ls
is 1
. How can I get that in a simple way?
# find the min of each sublist, then find the global min
min(map(min, ls))
# 1
# flatten `ls`, then find the min
min(y for x in ls for y in x)
# 1
# use itertools.chain to flatten `ls`
min(itertools.chain.from_iterable(ls))
# 1
ls = [[2, 3, 5], [8, 1, 10]] * 10000
%timeit min(y for x in ls for y in x) # 7.31 ms ± 64.9 µs
%timeit min([min(l) for l in ls]) # 6.24 ms ± 56.9 µs
%timeit min(map(min, ls)) # 5.44 ms ± 151 µs
%timeit min(min(ls, key=min)) # 5.28 ms ± 129 µs
%timeit min(itertools.chain.from_iterable(ls)) # 2.67 ms ± 62.5 µs
min_abs = min([min(l) for l in ls])