Python | Consecutive elements grouping in list
Sometimes, while working with Python lists, we can have a problem in which we might need to group the list elements on basis of their respective consecutiveness. This kind of problem can occur while data handling. Let’s discuss certain way in which this task can be performed.
Method : Using
enumerate() + groupby() + generator function + lambda
This task can be performed using the combination of above functions. In this, we create a generator function, in which we pass the list whose index-element are accessed using
enumerate() and grouped by consecutive elements using
groupby() and lambda. Works with Python2 only
The original list is : [1, 2, 3, 6, 7, 8, 11, 12, 13] Grouped list is : [(1, 3), (6, 8), (11, 13)]