Python if-else short-hand

PythonPython 2.7

Python Problem Overview


> Possible Duplicate:
> Ternary conditional operator in Python

I want to do the following in python:

while( i < someW && j < someX){
   int x = A[i] > B[j]? A[i++]:B[j++];
   ....
}

Clearly, when either i or j hits a limit, the code will break out of the loop. I need the values of i and j outside of the loop.

Must I really do

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

Or does anyone know of a shorter way?

Besides the above, can I get Python to support something similar to

a,b=5,7
x = a > b ? 10 : 11

Python Solutions


Solution 1 - Python

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.

Solution 2 - Python

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionlearnerView Question on Stackoverflow
Solution 1 - PythonLev LevitskyView Answer on Stackoverflow
Solution 2 - PythonDonCallistoView Answer on Stackoverflow