tags:

views:

140

answers:

4

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?

+17  A: 
>>> l = [4, 5, 12, 0, 3, 7]
>>> min(x for x in l if x > 5)
7
SilentGhost
lowercase ell is not a good choice for a variable name
Marius Gedminas
@Marius: have you actually downvoted me for this?
SilentGhost
+2  A: 
x = min(i for i in mylist if i > N)
Tim Pietzcker
+4  A: 
min(x for x in mylist if x > N)
Daniel Stutzbach
+3  A: 

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))
orangeoctopus
using filter is a little bit slower than using generator expressions
Xavier Combelle
+1. I've asked this question partly to improve my Python skills, so this answer serves my purpose quite well.
Cristi Diaconescu