Cristian Diaconescu
Cristian Diaconescu

Reputation: 35641

python - list operations

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?

Upvotes: 11

Views: 1185

Answers (4)

Donald Miner
Donald Miner

Reputation: 39893

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

Upvotes: 3

Daniel Stutzbach
Daniel Stutzbach

Reputation: 76667

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

Upvotes: 4

Tim Pietzcker
Tim Pietzcker

Reputation: 336158

x = min(i for i in mylist if i > N)

Upvotes: 2

SilentGhost
SilentGhost

Reputation: 319601

>>> l = [4, 5, 12, 0, 3, 7]
>>> min(x for x in l if x > 5)
7

Upvotes: 19

Related Questions