10

Someone just showed me this weird example of python syntax. Why is [4] working?

I would have expected it to evaluate to either [5] or [6], neither of which works. Is there some premature optimisation going on here which shouldn't be?

In [1]: s = 'abcd'

In [2]: c = 'b'

In [3]: c in s
 Out[3]: True

In [4]: c == c in s
Out[4]: True

In [5]: True in s
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-5-e00149345694> in <module>()
----> 1 True in s

TypeError: 'in <string>' requires string as left operand, not bool

In [6]: c == True
Out[6]: False

1 Answer 1

13

This is the same syntactic sugar that allows python to chain multiple operators (like <) together.

For example:

>>> 0 < 1 < 2
True

This is equivalent to (0<1) and (1<2), with the exception that the middle expression is only evaluated once.

The statement c == c in s is similarly equivalent to (c == c) and (c in s), which evaluates to True.

To highlight an earlier point, the middle expression is only evaluated once:

>>> def foo(x):
...     print "Called foo(%d)" % x
...     return x
...
>>> print 0 < foo(1) < 2
Called foo(1)
True

See the Python Language Reference for more detail.

Not the answer you're looking for? Browse other questions tagged or ask your own question.