+

# Python | Sequential grouping of items in a list

Method: Using ` enumerate () + groupby () ` + generator function + lambda
This task can be accomplished using a combination of the above functions. In this we create a generator function in which we pass a list, whose index element is accessed with ` enumerate () ` and grouped by successive elements with ` groupby () ` and lambda. Only works with Python2

 ` # Python code to demonstrate how it works ` ` # List of sequential elements ` ` # using enumerate () + groupby () + generator function + lambda ` ` import ` ` itertools `   ` # Function Utility Generator ` ` def ` ` groupc (test_list): ` ` for ` ` x, y ` ` in ` ` itertools.groupby (` ` enumerate ` ` (test_list), ` ` lambda ` ` (a, b): b ` - ` a): ` ` y ` ` = ` ` list ` ` (y) `` yield y [ 0 ] [ 1 ], y [ - 1 ] [ 1 ]    # initialize the list test_list = [ 1 , 2 , 3 , 6 , 7 , 8 , 11 , 12 , 13 ]   # print original list print ( "The original list is:" + str (test_list))    # List of sequential elements # using enumerate () + groupby () + generator function + lambda res = list < code class = "plain"> (groupc (test_list))   # print result print ( "Grouped list is: " + str (res)) `

Output:

` The original list is: [1, 2, 3, 6, 7, 8, 11, 12, 13] Grouped list is: [(1, 3), (6, 8), (11, 13)] `