Python | Altering duplicate values from given list

Many times we deal with the lists having identical numbers as a sequence and we wish to just keep the 1st occurrence of element and substituting all the occurrences with the different number. Let’s discuss certain ways in which this can be done.

Method #1 : Using list comprehension + enumerate()

This task can be achieved using the list comprehension for traversal and checking for element occurrence and index checking can be done using enumerate function.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate
# Altering duplicated
# using list comprehension + enumerate()
  
# initializing list
test_list = [2, 2, 3, 3, 3, 3, 4, 4, 5, 5, 5]
  
# printing original list
print("The original list : " + str(test_list))
  
# using list comprehension + enumerate()
# Altering duplicated
res = [False if (ele in test_list[ :idx]) else ele 
             for idx, ele in enumerate(test_list)]
  
# print result
print("The altered duplicate list is : " + str(res))

chevron_right


Output :

The original list : [2, 2, 3, 3, 3, 3, 4, 4, 5, 5, 5]
The altered duplicate list is : [2, False, 3, False, False, False, 4, False, 5, False, False]

 

Method #2 : Using itertools.groupby() + list comprehension

This particular task can also be performed using a combination of above function, using groupby function to get the groups of different elements and list comprehension to alter duplicates.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate
# Altering duplicated
# using itertools.groupby() + list comprehension
from itertools import groupby
  
# initializing list
test_list = [2, 2, 3, 3, 3, 3, 4, 4, 5, 5, 5]
  
# printing original list
print("The original list : " + str(test_list))
  
# using itertools.groupby() + list comprehension
# Altering duplicated
res = [val for key, grp in groupby(test_list) 
       for val in [key] + [False] * (len(list(grp))-1)]
  
# print result
print("The altered duplicate list is : " + str(res))

chevron_right


Output :

The original list : [2, 2, 3, 3, 3, 3, 4, 4, 5, 5, 5]
The altered duplicate list is : [2, False, 3, False, False, False, 4, False, 5, False, False]



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.