You can simply filter the tuples from the list as a generator expression and then you can stop taking the values from the generator expression when you get the first tuple whose second element is -1
, like this
>>> s = [(0,-1), (1,0), (2,-1), (3,0), (4,0), (5,-1), (6,0), (7,-1)]
>>> from itertools import takewhile
>>> X = 3
>>> list(takewhile(lambda x: x[1] != -1, (item for item in s if item[0] >= X)))
[(3, 0), (4, 0)]
Here, the generator expression, (item for item in s if item[0] >= X)
will give values one-by-one, on demand, (they are not generated all at once, so we save memory here) which are greater than or equal to X
.
Then, we take values from that generator expression, only till we find a tuple whose second element is not equal to -1
, with itertools.takewhile.