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

List comprehension: why does a conjunction not work?

Suppose the following:

>>>b = ['a/b', 'a b']
>>>[x for x in b if '/' in x]
['a/b']
>>>[x for x in b if ' ' in x]
['a b']
>>>[x for x in b if '/' and ' ' in x]
['a b']

My expectation is that[x for x in b if '/' and ' ' in x] should not return anything or at most an empty list. So why does [x for x in b if '/' and ' ' in x] return ['a b']?

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 :

If you examine your last list comprehension closely:

[x for x in b if '/' and ' ' in x]

you will see that you have two logical conditions. One is the string literal '/', and the other is ' ' in x. The first condition defaults to evaluating true, so the only real criterion here is that the string has to have a space. 'a b' meets this condition. Here is what you intended to do:

b = ['a/b', 'a b']
output = [x for x in b if '/' in x and ' ' in x]
print(output)  # []

Now all inputs fail, because none have both space and forward slash at the same time.

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