# Python | Remove consecutive duplicates from the list

Counters | Python Methods and Functions

Method # 1: Using ` groupby () ` + comprehension list
Using the groupby function, we can group the encountered elements as one and remove all duplicates in a row and just leave one element in the list.

 ` # Python3 demo code ` ` # removing consecutive duplicates ` ` # using groupby () + list comprehension ` ` from ` ` itertools ` ` import ` ` groupby `   ` # initializing list ` ` test_list ` ` = ` ` [` ` 1 ` `, ` ` 4 ` `, ` ` 4 ` `, ` ` 4 ` `, ` ` 5 ` `, ` ` 6 ` `, ` ` 7 ` `, ` ` 4 ` `, ` ` 3 ` `, ` ` 3 ` `, ` ` 9 ` `] `   ` # print original list ` ` print ` ` (` ` "The original list is:" ` ` + ` ` str ` ` (test_list)) `   ` # using groupby ( ) + list comprehension ` ` # removing consecutive duplicates ` ` res ` ` = ` ` [i [` ` 0 ` `] ` ` for ` ` i ` ` in ` ` groupby (test_list)] `   ` # print result ` ` print ` ` (` ` "The list after removing consecutive duplicates:" ` ` + ` ` str ` ` (res)) `

Exit:

` The original list is: [1, 4, 4, 4, 5, 6, 7, 4, 3, 3, 9] The list after removing consecutive duplicates: [1, 4, 5, 6, 7, 4, 3, 9] `

Method # 2: Using ` zip_ longest () ` + comprehension list
This function can be used to keep an element and remove subsequent elements using slicing. The zip_longest function performs the task of collecting values ​​in one list.

 ` # Python3 demo code ` ` # removing consecutive duplicates ` ` # using zip_longest () + list comprehension ` ` from ` ` itertools ` ` import ` ` zip_longest `   ` # initializing list ` ` test_list ` ` = ` ` [` ` 1 ` `, ` ` 4 ` `, ` ` 4 ` `, ` ` 4 ` `, ` ` 5 ` `, ` ` 6 ` `, ` ` 7 ` `, ` ` 4 ` `, ` ` 3 ` `, ` ` 3 ` `, ` ` 9 ` `] `   ` # print original list ` ` print ` ` (` ` "The original list is:" ` ` + ` ` str ` ` (test_list)) ` ` `  ` # using zip_longest () + comprehension list ` ` # removing consecutive duplicates ` ` res ` ` = [i for i, j in zip_longest (test_list, test_list [ 1 :]) `` if i! = j]   # print result print ( "List after removing consecutive duplicates:" +   str (res)) `

Exit:

` The original list is: [1, 4, 4, 4, 5, 6, 7, 4, 3, 3, 9] List after removing consecutive duplicates: [1, 4, 5, 6, 7, 4, 3, 9] `