7

I have a list

l = ['abc', 'abcdef', 'def', 'defdef', 'polopolo']

I'm trying to delete strings whose superstring is already in the list. In this case, the result should be:

['abcdef', 'defdef', 'polopolo']

I have written the code:

l=['abc','abcdef','def','defdef','polopolo']
res=['abc','abcdef','def','defdef','polopolo']
for each in l:
    l1=[x for x in l if x!=each]
    for other in l1:
        if each in other:
            res.remove(each)

but it doesnt seem to work. I have read that we cannot remove from the list while iterating over it. Hence the copy res, while l is my original list.

2
  • 1
    Your code would have worked if you broke out of the loop immediately after res.remove(each) :) For an efficient way to do this, please check my answer :) Commented Mar 6, 2014 at 11:29
  • pretty stupid mistake on my part now that you have explained it. :) Thank you Commented Mar 6, 2014 at 12:44

1 Answer 1

9
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']
Sign up to request clarification or add additional context in comments.

9 Comments

Try with ['abc','defghi' 'abcdef','def','defdef','defdef', 'polopolo']
@AshwiniChaudhary I get ['defghiabcdef', 'defdef', 'polopolo']. Is that wrong?
Duh! missed , after 'defghi', BTW 'defdef' count decreased to 1.
@AshwiniChaudhary Strictly speaking, a string is a substring of itself, right? ;)
Yes @thefourtheye.. your solution works, but can you point out why mine does not work?
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.