r/Python • • Feb 28 '13

What's the one code snippet/python trick/etc did you wish you knew when you learned python?

I think this is cool:

import this

259 Upvotes

307 comments sorted by

View all comments

Show parent comments

4

u/elsporko Feb 28 '13

How exactly does this work in Python? I've always wanted to do this in C/C++, but it's always been explained to me that it's impossible. How does Python handle it?

6

u/hogepiyo Feb 28 '13

Comparisons can be chained arbitrarily, e.g., x < y <= z is equivalent to x < y and y <= z, except that y is evaluated only once (but in both cases z is not evaluated at all when x < y is found to be false).

Formally, if a, b, c, ..., y, z are expressions and op1, op2, ..., opN are comparison operators, then a op1 b op2 c ... y opN z is equivalent to a op1 b and b op2 c and ... y opN z, except that each expression is evaluated at most once.

Note that a op1 b op2 c doesn’t imply any kind of comparison between a and c, so that, e.g., x < y > z is perfectly legal (though perhaps not pretty).

http://docs.python.org/2/reference/expressions.html#not-in

2

u/[deleted] Mar 01 '13

it's syntactic sugar for

if 3 <= x and x <= 9:

(with x evaluated only once of course)