List comprehension without 'for'

Viewed 2204

Often when working with lists in Python, I end up wanting to simply filter out items from a list.

numbers = [5, 1, 4, 2, 7, 4]
big_nums = [num for num in numbers if num > 2]

To me this seems unnecessarily verbose. I have to define and use num in two separate statements (num for num ...), even though I don't do any operation on num.

I tried [num in numbers if num > 2], but python throws a SyntaxError with this.

Is there a more concise way of doing this in Python?

Edit:

My question is if there is a better way to do what I'm trying to do in Python. There are many times where there's been a construct in Python I didn't know about, but which made my code better and more readable.

I am not asking about performance tradeoffs between filter and list comprehension. I have no problem with list comprehension, but I also had no problem with building lists with standard for loops before I learned about list comprehension.

1 Answers

Well, you could use filter, it's slower and not as readable but you don't need the for:

list(filter(lambda x: x > 2, numbers))

or:

list(filter((2).__lt__, numbers))

However using magic methods like this is fragile, this will only work if the list only contains integers. As Chris_Rands pointed out you normally use operator.lt instead:

from functools import partial
from operator import lt
list(filter(partial(lt, 2), numbers))

That would also work if the list contains other numeric types except int.

Related