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

python if/else statement with exception that keep elements if exist in another sub-list

Let us say I have the following tokens in list :

['I', 'want', 'to', 'learn', 'coding', 'in', 'r', 'and', 'c++', 'today', ',', 'and', 'then', 'I', "'ll", 'be', 'learning', 'c#', 'and', 'c']

I want to remove all tokens of length < 2 but want to keep elements of this sub-list:

['r','c','js','c#']

How can I do this in a single python list-comprehension ?

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

>Solution :

You can use list comprehension with two conditions.

lst1 = ['I', 'want', 'to', 'learn', 'coding', 'in', 'r', 'and', 'c++', 'today', ',', 'and', 'then', 'I', "'ll", 'be', 'learning', 'c#', 'and', 'c']

lst2 = ['r','c','js','c#']

res = [l for l in lst1 if (len(l)>=2) or (l in lst2)]
print(res)

['want',
 'to',
 'learn',
 'coding',
 'in',
 'r',
 'and',
 'c++',
 'today',
 'and',
 'then',
 "'ll",
 'be',
 'learning',
 'c#',
 'and',
 'c']
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