Write a Python program to pack consecutive duplicates of a given list elements into sublists code example

Example 1: Pack consecutive duplicates of list elements into sublists python

import itertools

def pack_consecutive_duplicates(_list: list):
    preprocessed_list = []
    # x groups the duplicates into a tuple ()
    # x[0] is the duplicate element
    # x[1] is a grouper iterable that conatins all the duplicate elements
    for x in itertools.groupby(_list):
        amount = [*x[1]].count(x[0])
        if amount > 1:
            for k in range(0, amount):
                preprocessed_list.append(x[0])
        else:
            preprocessed_list.append((x[0]))

    return preprocessed_list

Example 2: program to print duplicates from a list of integers in python

lst = [ 3, 6, 9, 12, 3, 30, 15, 9, 45, 36, 12, 12]
dupItems = []
uniqItems = {}
for x in lst:
   if x not in uniqItems:
      uniqItems[x] = 1
   else:
      if uniqItems[x] == 1:
         dupItems.append(x)
      uniqItems[x] += 1
print(dupItems)