Search code examples
pythonlistreducesimilarity

Python remove similar items from list


Using python, in the following list I need to remove phone numbers which are repeated with country codes.

['(+44)45860787163','(+27)16345860787','45860787163','16345860787']

I tried using Cartesian product and 'in' operator to compare strings but nothing seems to be working. What I'd like to keep are the full phone numbers.

['(+44)45860787163','(+27)16345860787']

Solution

  • Using list comprehension

    l = ['(+44)45860787163','(+27)16345860787','45860787163','16345860787']
    
    l = [x for x in l if '(' in x]
    
    print(l)
    
    >>> ['(+44)45860787163', '(+27)16345860787']
    

    If you want to be extra secure you can check for both semi colons

    l = [x for x in l if '(' in x and ')' in x]