1

This is a simple snippet of code that I have:

>>> test = ['asas', 'asa12', 'sdsdsd12', 'vccvcvcv', 'rertrtt11']
>>> for i in test:
...     if '11' in i:
...         print i
...
rertrtt11

Works as expected.Now to catch elements containing either 11 or 12,I do this :

>>> test = ['asas', 'asa12', 'sdsdsd12', 'vccvcvcv', 'rertrtt11']
>>> for i in test:
...     if '11' or '12' in i:
...         print i
...
asas
asa12
sdsdsd12
vccvcvcv
rertrtt11

That was unexpected.I was hoping to catch only the elements with 11 or 12 in it but the output contained all the elements.

While trying to troubleshoot,I tried an and operator to try to understand the behaviour:

>>> test = ['asas', 'asa12', 'sdsdsd12', 'vccvcvcv', 'rertrtt11']
>>> for i in test:
...     if '11' and '12' in i:
...         print i
...
asa12
sdsdsd12

Now I am thoroughly confused as I was expecting an empty set since there are no elements with both 11 and 12 in them.Is my understanding of operator functioning in python completely wrong ??

3 Answers 3

5

'11' or '12' in i is evaluated like this

('11') or ('12' in i)

So, the first part is always truthy. That is why all of them are printed. In the second case,

('11') and ('12' in i)

Here, first part is always Truthy, so it prints only the items which contain 12. You might want do

if '11' in i and '12' in i:

or

if all(item in i for item in ('11', '12')):

To have or condition, you can use any function, like this

if any(item in i for item in ('11', '12')):
Sign up to request clarification or add additional context in comments.

Comments

1

To give you a small and easy fix , you should try :

if (('11' in i) or ('12' in i)):
    #do something 

or

if (('11' in  i) and ('12' in i)):
    #do another thing 

This is not an unexpected error , Kindly refer to docs

Comments

1

The or and and operators do not chain the way you think they do.

if '11' and '12' in i: #this problem is the same for or

First python will perform '12' in i as in has a higher precedence than and. It will then and the return from the in test with '12', which is implicitly convertible to True.

To get the effect you actually want, you'd need to do:

if '11' in i and '12' in i: # same for or

This will properly check if '11' is in i, then if '12' is in i, then and/or the results of those two tests together.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.