I am trying to get a sample from a list based on a condition. It should be easy to do but I am unable to do it as following:
a = [2,4,5,9,1,6,4]
b = 6
c = [x for x in a if a < b]
I basically need a new list which should contain values less than 6. Any suggestions?
Or, the other way:
>>> a = [2,4,5,9,1,6,4]
>>> b = 6
>>> c = filter(lambda x: x < b, a)
>>> c
[2, 4, 5, 1, 4]
You almost had it as Ignacio pointed out:
>>> c = [x for x in a if x < b]
>>> c
[2, 4, 5, 1, 4]
The list comprehension is a longer way of writing this loop:
>>> c = []
>>> for x in a:
... if x < b:
... c.append(x)
...
>>> c
[2, 4, 5, 1, 4]
You missed. You need to compare each element, not the sequence.
c = [x for x in a if x < b]
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