How can I stop the iteration of list comprehension when a particular element is found For example:
list1=[a for a in list2 if a==someelement]
As soon as "a equals someelement",list1 should be set to a and no further iterations should be executed.
You might want to use takewhile.
>>> import itertools
>>> print(list(itertools.takewhile(lambda x: x<42, [2, 3, 4, 42, 5, 6, 7])))
[2, 3, 4]
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