Often when working with lists in Python, I end up just want to filter out the elements from the list.
numbers = [5, 1, 4, 2, 7, 4]
big_nums = [num for num in numbers if num > 2]
It seems to me too detailed. I have to define and use num in two separate ( num for num ...
) statements , although I do not perform any operations with num
.
I tried [num in numbers if num > 2]
, but python throws away SyntaxError
with this.
Is there a shorter way to do this in Python?
Edit:
My question is is there a better way to do what I'm trying to do in Python. There are many times when in Python, which I did not know about, there was a construction, but which made my code more understandable and understandable.
I am not asking about compromising performance between filter
and understanding the list. I have no problem understanding lists, but I also had no problems compiling lists with standard loops for
before I learned about list comprehension.
source
share