Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing duplicate elements in a list in Python?

Tags:

python

list

For example if I have a list as follows:

[3, 3, 3, 3, 3, 3, 100, 1, 1, 1, 1, 1, 1, 200, 3, 3, 3, 100, 1, 1, 1]

How can I remove the duplicate elements and represent the same element followed by the number of times it's repeating? Example Output:

[3, 6, 100, 1, 6, 200, 3, 3, 100, 1, 3]

Where 3 is repeating 6 times... 1 repeating 6 times... and so on

like image 797
heethesh Avatar asked Dec 05 '25 14:12

heethesh


1 Answers

You can use itertools.groupby with a generator function here:

>>> from itertools import groupby                                              
>>> lst = [3, 3, 3, 3, 3, 3, 100, 1, 1, 1, 1, 1, 1, 200, 3, 3, 3, 100, 1, 1, 1]
>>> def solve(seq):
    for k, g in groupby(seq):
        length = sum(1 for _ in g)
        if length > 1:
            yield k
            yield length
        else:
            yield  k
...             
>>> list(solve(lst))
[3, 6, 100, 1, 6, 200, 3, 3, 100, 1, 3]
like image 91
Ashwini Chaudhary Avatar answered Dec 07 '25 08:12

Ashwini Chaudhary



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!