Mike Scott
Mike Scott

Reputation: 293

Python "and" operator with ints

What is the explanation for this behavior in Python?

a = 10
b = 20
a and b # 20
b and a # 10

a and b evaluates to 20, while b and a evaluates to 10. Are positive ints equivalent to True? Why does it evaluate to the second value? Because it is second?

Upvotes: 10

Views: 330

Answers (3)

kurojishi
kurojishi

Reputation: 321

In python everything that is not None, 0, False, "", [], (), {} is True

a and b is readed as True and True in this case the same for b and a

and yes in this case it takes the first value

edit: incomplete as in the comments

Upvotes: 0

David Heffernan
David Heffernan

Reputation: 612804

The documentation explains this quite well:

The expression x and y first evaluates x; if x is false, its value is returned; otherwise, y is evaluated and the resulting value is returned.

And similarly for or which will probably be the next question on your lips.

The expression x or y first evaluates x; if x is true, its value is returned; otherwise, y is evaluated and the resulting value is returned.

Upvotes: 15

bgporter
bgporter

Reputation: 36474

See the docs:

x and y     if x is false, then x, else y

non-zero integers are treated as boolean true, so you get exactly the behavior described in the docs:

>>> a = 10
>>> b = 20
>>> a and b
20
>>> b and a
10

Upvotes: 4

Related Questions