Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's going on with this python syntax? (c == c in s)

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
like image 371
sapi Avatar asked Mar 14 '13 04:03

sapi


People also ask

What is the correct syntax in Python?

The correct syntax to create a Python List is using the square brackets. Creating a list is as simple as putting different comma-separated values between square brackets. Through this, using Lists you can store multiple items. A list can have integer, string or float elements.

Why is syntax important in Python?

The syntax of Python programming represents the rules or structure that control the layout of the keywords, symbols, punctuation, and other tokens of Python programming. Without syntaxes, programmers won't be able to extract the meaning or semantics of a language.


1 Answers

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.

like image 52
Moshe Avatar answered Nov 08 '22 09:11

Moshe