175

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 
10
  • @MartijnPieters: the second part certainly is a duplicate, but I'm not sure about the first one. Commented Jan 22, 2013 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? Commented Jan 22, 2013 at 15:25
  • @DSM: I also don't see anyone below addressing that part. ;-) Commented Jan 22, 2013 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. Commented Jan 22, 2013 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. Commented Jan 22, 2013 at 15:31

2 Answers 2

387

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.

Sign up to request clarification or add additional context in comments.

9 Comments

Thanks. This works for the second part of my question. Up vote!
I have edited to show that I need j and i outside of the while-loop.
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.
[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.
How does this work internally: x = a > b and 10 or 11
|
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 

3 Comments

10 if a > b else 11. No need to resort to boolean operators.
Thanks. This works for the second part of my question. Up vote!
How does this work internally: x = a > b and 10 or 11

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.