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
Author by
user3191569
Updated on June 19, 2022Comments
-
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 over 9 yearsWhere should
0
end up, if present? And don't name your own listlist
.
-
-
mgilson over 9 yearsYou can also use a generator expression here (and I'd advise against naming it
l
, maybelst
--l
looks too much like1
in some fonts. -
Two-Bit Alchemist over 9 yearsOK, 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 over 9 yearsTo 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.