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

Question:

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 ?

Asked By: aRedDish

||

Answers:

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']
Answered By: I'mahdi
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.