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
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With