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.