5

Given a list of integers, e.g.:

lst = [-5, -1, -13, -11, 4, 8, 16, 32]

is there a Pythonic way of retrieving the largest negative number in the list (e.g. -1) and the smallest positive number (e.g. 4) in the list?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
user3191569
  • 485
  • 1
  • 7
  • 24

1 Answers1

9

You can just use list comprehensions:

>>> some_list = [-5, -1, -13, -11, 4, 8, 16, 32]
>>> max([n for n in some_list if n<0])
-1
>>> min([n for n in some_list  if n>0])
4
Two-Bit Alchemist
  • 17,966
  • 6
  • 47
  • 82
  • 4
    You can also use a generator expression here (and I'd advise against naming it `l`, maybe `lst` -- `l` looks too much like `1` in some fonts. – mgilson Jan 14 '15 at 16:38
  • 1
    OK, I changed the variable name, though it's a bit beside the point for this. To use a generator expression instead change `[]` to `()`. I will leave the list form in the answer so it is clearer to anyone not familiar with it (like anyone with the same question as OP). – Two-Bit Alchemist Jan 14 '15 at 16:42
  • 4
    To use a generator expression, you can just drop the `[]` entirely. e.g. `max(n for n in some_list if n < 0)` which looks a lot cleaner after you've gotten used to it. – mgilson Jan 14 '15 at 16:53