Retrieve largest negative number and smallest positive number from list

15,582

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
Share:
15,582
user3191569
Author by

user3191569

Updated on June 19, 2022

Comments

  • user3191569
    user3191569 almost 2 years

    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
      jonrsharpe over 9 years
      Where should 0 end up, if present? And don't name your own list list.
  • mgilson
    mgilson over 9 years
    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.
  • Two-Bit Alchemist
    Two-Bit Alchemist over 9 years
    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).
  • mgilson
    mgilson over 9 years
    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.