I am trying to stop iterating through the for loop as soon as it comes across the number 5. Is there a way to add a break to this statement rather than just skip over the 5, in one line without importing anything?
(x for x in num if x != 5)
I am trying to stop iterating through the for loop as soon as it comes across the number 5. Is there a way to add a break to this statement rather than just skip over the 5, in one line without importing anything?
(x for x in num if x != 5)
Try itertools.takewhile
:
>>> from itertools import takewhile
>>> nums = [1, 2, 3, 4, 5, 6, 7, 8]
>>> list(takewhile(lambda x: x!=5, nums))
[1, 2, 3, 4]