Reputation: 185
I have a list of many values which i need to get rid of some values.
I want to get from all elements that don't fit. I need to have elements only in range(x, y).
I tried this:
K = [v > x and v < y for v in L]
However I get a list of True
and False
values...
How can I achieve that ?
Example:
L = [4, 5, 7]
range = [4, 6]
K = [5]
Upvotes: 1
Views: 75
Reputation: 8564
The expression a > b
is a boolean expression, which can be True
or False
, and moreover, you are taking the logical AND
of two boolean expressions, and thats why you get a list of True
and False
. If want to get the values in a given range, do this :
K = [i for i in L if (i > range[0] and i < range[1])]
Upvotes: 1
Reputation: 41168
The reason you get booleans is you're returning the result of the comparison rather than the value. Also Python chains the comparisons so you don't need to use and
:
K = [v for v in L if x < v < y]
Upvotes: 5
Reputation: 14856
Option 1:
`K = [v for v in L if v > num1 and v < num2]`
Option 2:
`K = filter(lambda x: x > num1 and x < num2, L)`
You should have added the if
otherwise you will get the boolean results...
Upvotes: 2