Reputation: 39
a = [0,1,2,3,4,5,6]
for x in a:
list(x < 4):
Expected Output: [0,1,2,3]
Actual Output: [True, True, True, True, False, False, False]
Any idea how to get what I want?
Upvotes: 1
Views: 104
Reputation: 4035
a = [0,1,2,3,4,5,6]
print ([x for x in a if x<4])
Output;
[0, 1, 2, 3]
>>>
Edit after comment: It's called list comprehension.
Upvotes: 8
Reputation: 17142
You can use filter
:
>>> a = [0,1,2,3,4,5,6]
>>> list(filter(lambda x: x < 4, a))
[0, 1, 2, 3]
or itertools.takewhile
(in case the list was sorted):
>>> from itertools import takewhile
>>> a = [0,1,2,3,4,5,6]
>>> list(takewhile(lambda x: x < 4, a))
[0, 1, 2, 3]
Upvotes: 5