views:

135

answers:

4

I have a list of integers and I want to create a new list with all elements smaller than a given limit.

a=range(15) #example list
limit=9 #example limit

My approach to solve this problem was

[i for i in a if i < limit]

To me the beginning 'i for i in' looks pretty verbose. Is there a better implementation in Python?

+1  A: 

You can use filter() (at least in the Python 2.x series... I think it might have been removed in 3.0)

newlist = filter(lambda item: item < limit, oldlist)

The first argument can be any callable (its result will be coerced to boolean, so it's best to use a callable that returns boolean anyway), and the second argument can be any sequence.

dcrosta
+4  A: 

You could use filter

>>> filter(lambda i: i < limit, a)
[0, 1, 2, 3, 4, 5, 6, 7, 8]

But list comprehensions are the preferred way to do it

Here is what python docs has to say about this:

List comprehensions provide a concise way to create lists without resorting to use of map(), filter() and/or lambda. The resulting list definition tends often to be clearer than lists built using those constructs.

Nadia Alramli
This is longer than the example list comprehension!
Triptych
+2  A: 

This is about the best you can do. You may be able to do better with filter, but I wouldn't recommend it. Bear in mind that the list comprehension reads almost like english: "i for i in a if i < limit". This makes it much easier to read and understand, if a little on the verbose side.

Jason Baker
A: 

The nicer versions require boilerplate code, so the list comprehension is as nice as you can get.

This would be one different way to do it:

from operator import ge
from functools import partial

filter(partial(ge, limit), a)

(But if you were to use filter, Nadia's way would be the obvious way to do it)

Roberto Bonvallet