Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is there a more efficient way to remove items from a list based on another list?

PUNCT_CHARS = { '(', ')', ',', ',', '、', ':', ':', '[', ']', '#'}

words = ['a', '#good', 'student']

for word in words.copy():
    for char in PUNCT_CHARS:
        if char in word:
            words.remove(word)
            break

print(words)

['a', 'student']

I want to remove words that contain punctuations. Can the 2nd for loop be replaced with an ‘any’ or ‘all’ function to make it more efficient?

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Take advantage of your PUNCT_CHARS set to check if the sets of characters are disjoint:

out = [w for w in words if PUNCT_CHARS.isdisjoint(w)]

Output: ['a', 'student']

To modify your original object:

words[:] = [w for w in words if PUNCT_CHARS.isdisjoint(w)]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading