How to extract consecutive even numbers from a list?
Solution 1:
To group items with shared criteria, you can use groupby
:
from itertools import groupby
nums = [3, 18, 6, 5, 3, 4, 32, 8, 12]
for is_even, grouper in groupby(nums, key=lambda x: x % 2 == 0):
if is_even:
evens = list(grouper) # grouper objects have no len. Must convert to list
if len(evens) >= 2: # only consider sequences of at least 2 even numbers
print(*evens)
Will give:
18 6
4 32 8 12