2

I started learning python within the last month. I recently came across a code example where a counter in the code was incremented based on a condition. The way the author did it was:

x = 0
x += [-1, 1][a == b]

From testing this works the same as if you used an if a==b: increment, else: decrement. I can't find this syntax anywhere else I've looked in the python documentation. It seems quite powerful and allows a variety of conditional assignments and aids conciseness.

Is there a reason I shouldn't use this structure also what is the structure doing?

3 Answers3

4

The Zen of Python says:

Explicit is better than implicit.
Simple is better than complex.
Readability counts.

Stick to the more explicit, readable and widely used version:

x += 1 if a == b else -1
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
  • To be fair, the author that OP mentioned probably simply wrote that expression before Python had its inline `if` syntax, which wasn't all that long ago. – Dolda2000 Aug 11 '14 at 15:10
  • @Dolda2000 maybe, but it really takes time to read and understand this, it is a bit of out of the ordinary and needs at least an extra comment. – alecxe Aug 11 '14 at 15:12
  • @alecxe agreed that is more readable. thanks for that clarification. – Sanalphatau Aug 11 '14 at 15:24
3

[a == b] evaluates to False or True which are effectively 0 or 1, so then that's used as the index into [-1, 1]...

So when a==b you get [-1, 1][1] (which is 1) or where they're not equal you get [-1, 1][0] (which is -1), the respective value is then added to x.

Jon Clements
  • 138,671
  • 33
  • 247
  • 280
  • ah i didn't realise you could use bools like that. are there any problems with doing this? – Sanalphatau Aug 11 '14 at 15:10
  • @Sanalphatau These days it's best to use the approach suggested by alecxe as it's far more readable and clear as to what the intent is (proven by the fact you've had to ask what's going on) – Jon Clements Aug 11 '14 at 15:12
  • accepted this as it directly answers the Q though alecxe's comments are relevant to actual application. – Sanalphatau Aug 11 '14 at 15:27
2

Some would call it a hack, and it can be difficult to read (as evidenced by this question) but it's equivalent to:

x = 0
if(a == b):
    x += 1
else:
    x -= 1

Because the integer version of the (boolean) result of a == b is 0 or 1.

flau
  • 1,328
  • 1
  • 20
  • 36
  • Any reason for downvote? – flau Aug 11 '14 at 15:12
  • Not from me, but your logic is the wrong way round. – Ian Clark Aug 11 '14 at 15:13
  • 1
    I'll reset you to zero. The only other thing I can think of which might have annoyed the downvoter is your matter-of-fact "it's pretty unreadable". Perhaps it would be better to say "some people might think..." - and Zen of Python quotes always go down a treat :P – Ian Clark Aug 11 '14 at 15:21