Delete substrings from a list of strings

l=['abc','abcdef','def','defdef','polopolo']
print [j for i, j in enumerate(l) if all(j not in k for k in l[i + 1:])]
# ['abcdef', 'defdef', 'polopolo']

We can speed it up a very little, by sorting the list before

l = sorted(l, key = len)
print [j for i, j in enumerate(l) if all(j not in k for k in l[i + 1:])]

As @Ashwini Chaudhary mentions in the comments, if you want to retain the duplicate strings, then you can do this

l = ['abc','defghi' 'abcdef','def','defdef','defdef', 'polopolo']
l = sorted(l, key = len)
print [j for i,j in enumerate(l) if all(j == k or (j not in k) for k in l[i+1:])]
# ['defdef', 'defdef', 'polopolo', 'defghiabcdef']

Leave a Comment