2

In ruby I can do this:

1.9.3-p448 :001 > a = 1 || 2
 => 1 
1.9.3-p448 :004 > a = nil || 2
 => 2 
1.9.3-p448 :005 > a = 1 || nil
 => 1 

Is there a similar one-liner in Python?

0

3 Answers 3

7

Just use the or operator. From the linked page:

x or y: if x is false, then y, else x

Example:

In [1]: 1 or 2
Out[1]: 1

In [2]: None or 2
Out[2]: 2

In [3]: 1 or None
Out[3]: 1
Sign up to request clarification or add additional context in comments.

2 Comments

Note that this also "works" for False or 2 == 2, 0 or 2 == 2, and [] or [2] == [2]. Make sure you want this behaviour
@Eric: good point. The OP used ||, and 0 || 2 gives 0 in Ruby (compared with 0 | 2, which gives 2), so we'd need to check on expectations in those cases.
4

Python's or operator is pretty much the equivalent of Ruby's || -- and None can be used in Python somewhat similarly to how nil is in Ruby.

So, for example,

a = None or 2

would set a to 2.

You can also use a richer "ternary" operator, something if condition else somethingelse -- a or b is the same as a if a else b -- but clearly or is more concise and readable when what you want to do is exactly the semantics it supports.

1 Comment

I think in Ruby the null syntax is nil, not null. But I agree with the rest of the answer.
1

Don't forget about modern if-else syntax:

x = a if a is not None else 999

(or whatever condition you need). This let you test for non-None and is not prone to empty list and similar problems.

General syntax is

ValueToBeUsedIfConditionIsTrue if Condition else ValueToBeUsedIfConditionIsFalse

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.