7

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)
2
  • You could put a break inside the if - no point adding any item to final more than once. Commented Nov 5, 2019 at 13:43
  • This is a highly rated question, so I presume I’m the only dumb person here, but... Please find a way to indicate what it is you want with a question, rather than having us puzzle it out from your code. That could be as simple as just printing the desired output, since you seem to be happy with the result, just not with the method. Commented Nov 5, 2019 at 17:14

2 Answers 2

4

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

2 Comments

your code retains duplicate in output if present in the initial list while OP's solution doesn't do that
you can also use filter, which is basically the same: list(filter(not any(element in other and element != other for other in a), set(a)))
2

Another approach:

set([i for i in a if not any(set(i) < set(j) for j in a)])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.