11

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?

2
  • 1
    What do you mean by "READABLE"? Commented Jul 19, 2010 at 14:55
  • @SLott "read·a·ble/ˈrēdəbəl/: (2) Easy or enjoyable to read." What do you mean by "What do you mean by readable?" ? Commented Jul 21, 2010 at 14:40

4 Answers 4

19
>>> l = [4, 5, 12, 0, 3, 7]
>>> min(x for x in l if x > 5)
7
Sign up to request clarification or add additional context in comments.

Comments

4
min(x for x in mylist if x > N)

Comments

3

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))

2 Comments

using filter is a little bit slower than using generator expressions
+1. I've asked this question partly to improve my Python skills, so this answer serves my purpose quite well.
2
x = min(i for i in mylist if i > N)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.