-2

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?

cs95
  • 379,657
  • 97
  • 704
  • 746
lfvv
  • 1,509
  • 15
  • 17
  • `min(elem for subls in ls for elem in subls)` – jdehesa Jun 28 '19 at 18:00
  • What did you try so far? Please read https://stackoverflow.com/help/minimal-reproducible-example – RafazZ Jun 28 '19 at 18:00
  • The proposed dupe ([Optimise a minimum operation on a python list of list](https://stackoverflow.com/q/56668205/1782792)) had very little to do with this question. – jdehesa Jun 28 '19 at 18:10
  • @cs95 Ah sorry I didn't see that, sure do close it if you found a proper dupe (I couldn't find it myself). That's a more general case, but if it's good for you it is for me. – jdehesa Jun 28 '19 at 18:26
  • @jdehesa it isn't a perfect dupe, just a little more general. I'll go ahead and close it again. – cs95 Jun 28 '19 at 18:29

3 Answers3

4
# 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
cs95
  • 379,657
  • 97
  • 704
  • 746
1
min_abs = min([min(l) for l in ls])
lfvv
  • 1,509
  • 15
  • 17
  • 1
    you can skip the `[` and `]`, and it avoid the temporary list. – jdehesa Jun 28 '19 at 18:01
  • Building a list of min values like this is a little more wasteful than it needs to be. See [here](https://stackoverflow.com/a/56811402/4909087) for a timings comparison. – cs95 Jun 30 '19 at 15:02
1

You can simply try this:

res = min(min(ls, key=min))
Anubhav Singh
  • 8,321
  • 4
  • 25
  • 43