1

I get following output with and operator

code

>>>0 and []
0
>>>[] and 0
[]
>>> 0 and ''
0
>>>'' and 0
''

I could not figure out about on what basis I m getting different result on the basis of placing of elements..

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
ceasif
  • 345
  • 2
  • 14
  • 1
    `x and y` is equivalent to `y if x else x`. Similar, `x or y` is `x if x else y` which is handy for assigning default values. – tobias_k Jun 23 '14 at 15:12
  • It's not clear to me why Martijn Pieters marked this a duplicate of short circuiting. This has nothing to do with short circuiting. Truthiness is not an issue of short circuiting, and the answer in Python would be the same with or without it. – John Haugeland Jun 23 '14 at 15:18

1 Answers1

2

From the docs on and:

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.

In your case, because 0, '', and [] all evaluate to False, the first value in each of your expressions is being returned.

mdml
  • 22,442
  • 8
  • 58
  • 66
  • Wow, you somehow managed to post this 11 seconds after the question was closed. :-) – tobias_k Jun 23 '14 at 15:16
  • @tobias_k: there is a 4 hour window, actually. The *full web UI* disables the post button, but the mobile UI does not. If you started posting before the question got closed, you can still get in. – Martijn Pieters Jun 23 '14 at 15:17