Search code examples
pythonlistlist-comprehension

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 ?


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