Is there a way to use two if conditions in list comprehensions in python

Question:

Suppose I had a list

my_list = ['91 9925479326','18002561245','All the best','good']

Now I want to ignore the strings in the list starting with 91 and 18 like below

result = []
for i in my_list:
   if not '91' in i:
      if not '18' in i:
         result.append(i) 

So here I want to achieve this with list comprehensions.

Is there anyway to write two if conditions in list compreshensions?

Answers:

[i for i in my_list if '91' not in i and '18' not in i]

Note you shouldn’t use list as a variable name, it shadows the built-in function.

Answered By: Daniel Roseman

You can “merge” both conditions:

if ((not '91' in i) and (not '18' in i))
Answered By: heltonbiker

If you have more than two values (91 and 18)
or they are dynamically produced
it is better to use this construction:

[i for i in my_list if not i.startswith(('91', '18'))]

Or if you want to check if 91 and 18 are in the strings (not only in the beginning), use in instead of startswith:

[i for i in my_list if all(x not in i for x in ['91', '18'])]

Example of usage:

>>> my_list = ['91 9925479326','18002561245','All the best','good']
>>> [i for i in my_list if all(not i.startswith(x) for x in ['91', '18'])]
['All the best', 'good']
>>> 
Answered By: Igor Chubin
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.