import itertools my_list = [7, 6, -3, -3, -8, 2, -5, 4, -8, -2, -6, -1] is_negative = [True if num < 0 else False for num in my_list] groups = itertools.groupby(is_negative) occurrences_of_negatives = [len(list(g)) for k, g in groups if k] result = max(occurrences_of_negatives)
Explanation:
First, create a new is_negative list to get only 2 categories :
True for negative numbers,False for all others.
In our case, we get from the list my_list :
[ 7, 6, -3, -3, -8, 2, -5, 4, -8, -2, -6, -1 ]
such a list is_negative :
[False, False, True, True, True, False, True, False, True, True, True, True]`
Then, itertools.groupby() function itertools.groupby() we obtain from it groups of consecutive values — something like a dictionary, although this is not a dictionary — in our case
{False: [False, False], True: [True, True, True], False: [False], True: [True], False: [False], True: [True, True, True, True]}
From it we will build the list only for True keys , and we are only interested in the lengths of suitable lists. In our case, the occurrences_of_negatives list will be as follows:
[3, 1, 4]
And this is almost everything - the result will be the maximum value in this list.