165

Suppose I have some code like:

if A[i] > B[j]:
    x = A[i]
    i += 1
else:
    x = B[j]
    j += 1

Is there a simpler way to write it? Does Python offer syntax similar to this?

x = (A[i] > B[j]) ? A[i] : B[j]
((A[i] > B[j]) ? i : j) += 1
Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
learner
  • 11,490
  • 26
  • 97
  • 169
  • @MartijnPieters: the second part certainly is a duplicate, but I'm not sure about the first one. – DSM Jan 22 '13 at 15:24
  • @DSM: well, the first part won't be needed once more pythonic structures and loops are discovered by the OP.. Are you going to try and write a full introduction into iterators? – Martijn Pieters Jan 22 '13 at 15:25
  • @DSM: I also don't see anyone below addressing that part. ;-) – Martijn Pieters Jan 22 '13 at 15:26
  • 5
    @Martijn Pieters , while I am thankful for all participations, your comment is rather cheap. If you have an answer for the first part, post it. Ridicule is not reasoning. – learner Jan 22 '13 at 15:29
  • @user1612593: I'm sorry, I don't mean to ridicule you. It takes time to get used to a new language and it's idioms. There is too little context here to give a concise and meaningful answer; you mostly do not encounter situations like yours in idiomatic Python. – Martijn Pieters Jan 22 '13 at 15:31
  • @user1612593: I know MP (net-know, anyhow! :^), and he wasn't intending ridicule, he was being literal. There's no slick syntax to do exactly what you want in Python, but that's not a problem because with with tools like `zip` and `enumerate` we don't need to. – DSM Jan 22 '13 at 15:33
  • I have edited to show that I need j and i outside of the while-loop. – learner Jan 22 '13 at 15:46
  • @user1612593: You are basically looping over the sorted concatenation of A and B; use `for x in sorted(A + B):` for that; the [Python sort implementation](http://en.wikipedia.org/wiki/Timsort) can handle a merge like that very efficiently. Or write a generator that takes `A` and `B` as inputs, calls `iter()` on them, and yields the smaller next value of either. – Martijn Pieters Jan 22 '13 at 16:22
  • @user1612593: (Very) generic generator to do the same job: https://gist.github.com/4596098 – Martijn Pieters Jan 22 '13 at 16:36
  • `X if condition else Y` If condition is true evaluate X else evaluate Y – mrSaraf Sep 16 '19 at 09:24

2 Answers2

362

The most readable way is

x = 10 if a > b else 11

but you can use and and or, too:

x = a > b and 10 or 11

The "Zen of Python" says that "readability counts", though, so go for the first way.

Also, the and-or trick will fail if you put a variable instead of 10 and it evaluates to False.

However, if more than the assignment depends on this condition, it will be more readable to write it as you have:

if A[i] > B[j]:
  x = A[i]
  i += 1
else:
  x = A[j]
  j += 1

unless you put i and j in a container. But if you show us why you need it, it may well turn out that you don't.

Lev Levitsky
  • 63,701
  • 20
  • 147
  • 175
  • Thanks. This works for the second part of my question. Up vote! – learner Jan 22 '13 at 15:25
  • I have edited to show that I need `j` and `i` outside of the while-loop. – learner Jan 22 '13 at 15:42
  • 1
    `x = a > b and 10 or 11` also works correctly in a specific set of problems, because anything that evaluates to false instead of `10` would make it fail, for example, a String. – Ihor Husar Nov 09 '15 at 16:52
  • 1
    `[i<2 and i or i-4 for i in range(4)]` returns: `[-4, 1, -2, -1]`. It trolled me for two days and I had to actually read code line by line with my professor to figure out why our algorithm doesn't work. Thanks. – Ch3shire Jan 17 '17 at 10:59
  • How does this work internally: x = a > b and 10 or 11 – variable Nov 09 '19 at 05:18
  • is there a way to make it without "else"? – Liker777 Aug 14 '22 at 04:55
  • @Liker777 to make _what_? Short answer: you can have an `if` _statement_ without an `else` clause. But you cannot have a ternary _expression_ without the `else` part, because an expression needs to have a value in all cases. – Lev Levitsky Aug 15 '22 at 10:43
  • @LevLevitsky I am not sure I understand your question "to make what". To make an if statement without else because it is shorter and more readable and cleans up the code.. Or do you mean something else? Ternary operator serves the same goal. – Liker777 Aug 16 '22 at 12:01
  • @Liker777 that's exactly the distinction I was trying to make. [Conditional expressions](https://docs.python.org/3/reference/expressions.html#conditional-expressions) must have "else" in them. In [`if` statements](https://docs.python.org/3/reference/compound_stmts.html#if) they are optional. – Lev Levitsky Aug 16 '22 at 13:51
22

Try this:

x = a > b and 10 or 11

This is a sample of execution:

>>> a,b=5,7
>>> x = a > b and 10 or 11
>>> print x
11
DonCallisto
  • 29,419
  • 9
  • 72
  • 100