Change language

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 " 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)] 

Shop

Learn programming in R: courses

$

Best Python online courses for 2022

$

Best laptop for Fortnite

$

Best laptop for Excel

$

Best laptop for Solidworks

$

Best laptop for Roblox

$

Best computer for crypto mining

$

Best laptop for Sims 4

$

Latest questions

NUMPYNUMPY

Common xlabel/ylabel for matplotlib subplots

12 answers

NUMPYNUMPY

How to specify multiple return types using type-hints

12 answers

NUMPYNUMPY

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

12 answers

NUMPYNUMPY

Flake8: Ignore specific warning for entire file

12 answers

NUMPYNUMPY

glob exclude pattern

12 answers

NUMPYNUMPY

How to avoid HTTP error 429 (Too Many Requests) python

12 answers

NUMPYNUMPY

Python CSV error: line contains NULL byte

12 answers

NUMPYNUMPY

csv.Error: iterator should return strings, not bytes

12 answers

News


Wiki

Python | How to copy data from one Excel sheet to another

Common xlabel/ylabel for matplotlib subplots

Check if one list is a subset of another in Python

sin

How to specify multiple return types using type-hints

exp

Printing words vertically in Python

exp

Python Extract words from a given string

Cyclic redundancy check in Python

Finding mean, median, mode in Python without libraries

cos

Python add suffix / add prefix to strings in a list

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

Python - Move item to the end of the list

Python - Print list vertically