Find groups of strictly increasing numbers in a list in Python

Sometimes we may need to evaluate if the elements in a list are strictly incremental. Which means the numbers are increasing with a gap of 1. In this article we will see how to find out the groups of strictly increasing numbers in a given list.

Direct comparison

In this approach we gradually increase the index of each number and compare it with previous number in the list. As long as the second number is 1 greater than the first, we append the numbers to a inner list. Else the number becomes part of the outer list.

Example

Live Demo

listA = [11, 12, 6, 7, 8, 12, 13,14]
res = [[listA[0]]]

for i in range(1, len(listA)):
if listA[i - 1] + 1 == listA[i]:
res[-1].append(listA[i])

else:
res.append([listA[i]])

print(res)

Output

Running the above code gives us the following result −

[(11, 12), (6, 7, 8), (12, 13, 14)]

With itertools

In this approach we use the itertools and its functions to get the set of strictly incrementing numbers.

Example

Live Demo

from itertools import groupby, cycle

def groupincreasing(l):
inner_list = cycle(listA)

next(inner_list)
groups = groupby(l, key=lambda j: j + 1 == next(inner_list))
for k, v in groups:
if k:
yield tuple(v) + (next((next(groups)[1])),)

listA = [11, 12, 6, 7, 8, 12, 13,14]
print(list(groupincreasing(listA)))

Output

Running the above code gives us the following result −

[(11, 12), (6, 7, 8), (12, 13, 14)]
Published on 26-Aug-2020 07:47:14