How to remove substrings from a python list

Is there any list comprehension technique to get the below-desired result in a better way

a = ['hello', 'world', 'hello world', 'hello world how are', 'hello india']

final = set()
for i in a:
    for j in [x for x in a if x != i]:
        if i in j:
            final.add(i)
list(set(a)^final)
Trainee Asked on November 5, 2019 in Python.
Add Comment
1 Answer(s)

Shorter but not necessarily better:

print([x for x in a if not any(x in j for j in a if x != j)])

With removing of duplicates in the final list (resembles behavior from question):

print(list(set(x for x in a if not any(x in j for j in a if x != j))))
Reviewer Answered on November 5, 2019.
Add Comment

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.