Search code examples
pythonstringlistnltkoperation

I need to create a list only with the repeated items from another list


I have a list with repeated items like:

    Movies = ['Batman Return', 'Minions', 'Slow Burn', 
'Defensor', 'Minions', 'Batman Return', 
'All is lost', 'Minions']

You can see that there are two repeated items, and I need created a list with only this elements like that:

Top_Movies = ['Batman Return', 'Minions']

Order is important.

I know how delete repeated items but I don't know how to do the opposite.


Solution

  • you can use collections.Counter:

    from collections import Counter
    
    
    Movies = ['Batman Return', 'Minions', 'Slow Burn', 
    'Defensor', 'Minions', 'Batman Return', 
    'All is lost', 'Minions']
    
    Top_Movies = [k for k, v in Counter(Movies).items() if v > 1]
    Top_Movies
    

    output:

    ['Batman Return', 'Minions']
    

    the order is guaranteed if you use a python version >= 3.6