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

python "in" operation comparing a string with a tuple of containing only 1 string

I notice a strange behavior of "in" operation when comparing a string with a tuple containing only 1 string.

'monday' in ('not monday')

the result is True
as if we were comparing 2 strings

but if I change the expression by adding another element in the tuple.

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

'monday' in ('not monday', 'not monday neither')

it returns False as expected.

any idea why?

>Solution :

>>> 'monday' in ('not monday')
True
>>> 'monday' in ('not monday',)
False

A single-element tuple must have the trailing comma. Otherwise, it gets interpreted as regular order-of-operations parentheses, which are meaningless in this case So, 'monday' in ('not monday') is syntatically identical to 'monday' in 'not monday'.

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