Retrieve largest negative number and smallest positive number from list

user3191569 picture user3191569 · Jan 14, 2015 · Viewed 13.4k times · Source

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?

Answer

Two-Bit Alchemist picture Two-Bit Alchemist · Jan 14, 2015

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