Python | Truncate the specified list for duplicate items



Examples :

  Input:  [1, 1, 1, 2, 3, 3, 3, 4, 4, 4, 4 ]  Output:  [(1, 3), (2, 1), (3, 3), (4, 4)]  Input:  [`alice`,` alice`, `bob`]  Output:  [(` alice`, 2), (`bob`, 1)] 

Approach # 1: brute force
This is a naive approach to shorten the list. Another list is required, say “tup_list”. Initialize the index to 0 and use a loop to check how many times each unique element of the list is repeated. Once you find the element and its number of repetitions, add it to the list as a tuple.

# Python3 list-shortening program
# for repeating elements

 

def shrinkList (lst):

tup_list = []

i, index = 0 , 0

while (index & lt; len (lst)):

  element_count = 0

while (i & lt;  len (lst) and lst [i] = = lst [index]) :

element_count + = 1

i + = 1

tup_list.append ((lst [index], element_count))

index + = element_count

 

retu rn tup_list

 
Driver code

lst = [ 1 , 1 , 1 , 2 , 2 , 3 , 3 , 4 ]

print (shrinkList (lst))

Exit:

 [(1, 3), (2 , 2), (3, 2), (4, 1)] 

Approach # 2: Alternative brute force
This is another brute force method that is used t loop to traverse the list. It uses the prev_element variable to hold the previous element. First, it checks if it is the first unique element or not, if so, it increments the counter and stores the element in prev_element. If the item is repeating, just increase the counter. If all these cases are not true, then just add a prev_element element and count it as a tuple in the tup_list.

# Python3 program to shorten the list
# for repeating elements

 

def shrinkList (lst):

  prev_element = None

  count = 0

tup_list = []

 

  for ele in lst:

if (prev_element = = ele): 

count + = 1

  

elif (prev_element is None ):

count + = 1

prev_element = ele

  

  else :

tup_list.append ((prev_element, count))

count = 1

prev_element = ele

 

tup_list.append ((prev_element, count))

return tup_list

 
Driver code

lst = [ 1 , 1 , 1 , 2 , 2 , 3 , 3 , 4 ]

print (shrinkList (lst))

Exit:

 [(1, 3) , (2, 2), (3, 2), (4, 1)] 

Approach # 3. Using Itertools.groupby ()
This is more pythonic approach to solving this problem.  itertools.groupby () creates an iterator that returns sequential keys and groups from the iterable. It groups similar elements and returns the elements and their count as a list of tuples.

# Python3 list-shortening program
# for repeating elements

from itertools import groupby

 

def shrinkList (lst):

return ([(element, len ( list (i)))

  for element, i in groupby (lst)])

  
Driver code

lst = [ 1 , 1 , 1 , 2 , 2 , 3 , 3 , 4 ]

print (shrinkList (lst ))

Exit:

 [ (1, 3), (2, 2), (3, 2), (4, 1)]