Categories
Python Answers

How to detect consecutive integers in a list with Python?

Spread the love

Sometimes, we want to detect consecutive integers in a list with Python.

In this article, we’ll look at how to detect consecutive integers in a list with Python.

How to detect consecutive integers in a list with Python?

To detect consecutive integers in a list with Python, we can use the itertools.groupby method.

For instance, we write

from itertools import groupby
from operator import itemgetter

data = [1, 4, 5, 6, 10, 15, 16, 17, 18, 22, 25, 26, 27, 28]
for k, g in groupby(enumerate(data), lambda (i, x): i - x):
    print map(itemgetter(1), g)

to call groupby with the data list and a function that returns i - x.

We group by the value of i - x to group consecutive integers together.

Then we call map to get the get the first item from group g.

Conclusion

To detect consecutive integers in a list with Python, we can use the itertools.groupby method.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *