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'.

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']

Leave a Reply