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

How to remove items from list that have more then 20 characters?

I have a list, inside of list I have items. Some of items have more then 20 characters and I want to remove those items. But I don’t want to remove items that have spaces. I provide minimal reproducible example…

This is a list…

list = ['one', 'two', 'three', 'black', 'verylongcharacterwords', 'very long character words']

I want to remove 'verylongcharacterwords', but I don’t want to remove 'very long character words'.

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

This is wanted output…

new_list = ['one', 'two', 'three', 'black', 'very long character words']

Thanks in advance!

>Solution :

List comprehensions to the rescue:

>>> lst = ['one', 'two', 'three', 'black', 'verylongcharacterwords', 'very long character words']
>>> [l for l in lst if not any(len(w) > 20 for w in l.split())]
['one', 'two', 'three', 'black', 'very long character words']
>>>
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