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)
Use the String translate() method to remove all occurrences of a substring from a string in python.
There are multiple ways to remove whitespace and other characters from a string in Python. The most commonly known methods are strip() , lstrip() , and rstrip() . Since Python version 3.9, two highly anticipated methods were introduced to remove the prefix or suffix of a string: removeprefix() and removesuffix() .
To remove a substring from a string, call the replace() method, passing it the substring and an empty string as parameters, e.g. str. replace("example", "") . The replace() method will return a new string, where the first occurrence of the supplied substring is removed.
We can remove an item from the list by passing the value of the item to be deleted as the parameter to remove() function. pop() is also a method of list. We can remove the element at the specified index and get the value of that element using pop().
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))))
Another approach:
set([i for i in a if not any(set(i) < set(j) for j in a)])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With