Python: Remove elements from the list which are prefix of other
Question: Fastest (& python) way to get list of elements which do not contain any other
elements as their prefix.

(Elements can be in any order, for the sake of clarity in explanation elements
are kept kind of sequential here, so if needed sorting has to be done
explicitly)

Input is

    
    
    ['AB', 'ABC', 'ABCDEF', 'ABCDEFG', 'BCD', 'DEF', 'DEFGHI', 'EF', 'GKL', 'JKLM']
    

Elements eliminated:

    
    
    'AB' prefix of 'ABC'
    'ABC' prefix of 'ABCDEF'
    'ABCDEF' prefix OF 'ABCDEFG'
    'DEF' prefix of 'DEFGHI'
    

Expected Output

    
    
    ['ABCDEFG', 'BCD', 'DEFGHI', 'EF', 'GKL', 'JKLM']
    

**Edited** :

Adding a bit more complexity(or clarity). The average length of the list
varies from 500 - 900.


Answer: List comprehension (`ls` is the name of your input list):

    
    
    [x for x in ls if x not in [y[:len(x)] for y in ls if y != x]]
    

I doubt it is the quickest in terms of performance, but the idea is very
straightforward. You are going through the list element by element and
checking if it is the prefix of any element in a list of all the rest of
elements.

timeit result: 11.9 us per loop (though the scaling is more important if you
are going to use it for large lists)

