Remove a string that is a substring of other string in the list WITHOUT changing original order of the list
<p>I have a list.</p>

<pre><code>the_list = ['Donald Trump has', 'Donald Trump has small fingers', 'What is going on?']
</code></pre>

<p>I'd like to remove "Donald Trump has" from <code>the_list</code> because it's a substring of other list element.</p>

<p>Here is an important part. I want to do this without distoring the order of the original list.</p>

<p>The function I have (below)  distorts the order of the original list. Because it sorts the list items by its length first. </p>

<pre><code>def substr_sieve(list_of_strings):  
    dups_removed = list_of_strings[:]
    for i in xrange(len(list_of_strings)):
        list_of_strings.sort(key = lambda s: len(s))
        j=0
        j=i+1
        while j &lt;= len(list_of_strings)-1:
            if list_of_strings[i] in list_of_strings[j]:
                try:
                    dups_removed.remove(list_of_strings[i])
                except:
                    pass
            j+=1
    return dups_removed
</code></pre>

<p>You can just recursively reduce the items.</p>

<p>Algorithm:</p>

<p>Loop over each item by popping it, decide if it needs to be kept or not.
Call the same function recursively with the reduced list.
Base condition is if the list has at-least one item (or two?).</p>

<p>Efficiency: It might not be the most efficient. I think some Divide and Conquer methods would be more apt?</p>

<pre><code>the_list = ['Donald Trump has', 'Donald Trump has small fingers',\
            'What is going on?']

final_list = []

def remove_or_append(input):
    if len(input):
        first_value = input.pop(0)
        found = False
        for each in input:
            if first_value in each:
                found = True
                break
            else:
                continue
        for each in final_list:
            if first_value in each:
                found = True
                break
            else:
                continue
        if not found:
            final_list.append(first_value)
        remove_or_append(input)

remove_or_append(the_list)

print(final_list)
</code></pre>

<p>A slightly different version is:</p>

<pre><code>def substring_of_anything_else(item, list):
    for idx, each in enumerate(list):
        if idx == item[0]:
            continue
        else:
            if item[1] in each:
                return True
        return False

final_list = [item for idx, item in enumerate(the_list)\ 
              if not substring_of_anything_else((idx, item), the_list)]
</code></pre>

python string list