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?
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.
If you don't want duplicates, use a Set instead of a List . To convert a List to a Set you can use the following code: // list is some List of Strings Set<String> s = new HashSet<String>(list); If really necessary you can use the same construction to convert a Set back into a List .
Compare the size of set and list. If size of list & set is equal then it means no duplicates in list. If size of list & set are different then it means yes, there are duplicates in list.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With