Given a list of unsorted numbers, I want to find the smallest number larger than N (if any).
In C#, I'd do something like this (checks omitted) :
var x = list.Where(i => i > N).Min();
What's a short, READABLE way to do this in Python?
>>> l = [4, 5, 12, 0, 3, 7]
>>> min(x for x in l if x > 5)
7
min(x for x in mylist if x > N)
Other people have given list comprehension answers. As an alternative filter
is useful for 'filtering' out elements of a list.
min(filter(lambda t: t > N, mylist))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With