Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove substrings from a python list

Tags:

python

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)
like image 500
ssharma Avatar asked Nov 05 '19 13:11

ssharma


People also ask

How do I remove a specific substring from a list in Python?

Use the String translate() method to remove all occurrences of a substring from a string in python.

How do I remove a suffix 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() .

How do I remove a substring?

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.

How do you remove an item from a list in Python?

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().


2 Answers

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))))
like image 57
Michael Butscher Avatar answered Nov 03 '22 03:11

Michael Butscher


Another approach:

set([i for i in a if not any(set(i) < set(j) for j in a)])
like image 38
zipa Avatar answered Nov 03 '22 04:11

zipa