Python: shortcut conditional expression

Viewed 289

the shortcut conditional expression :
expression1 if condition else expression2
x=1 if a>3 else 2
But: can I have 2 expressions at the start ?
x=1,b=3 if a>3 else 2

Thanks to > idontknow, solution is >

    previousTime,BS_Count=(db_row_to_list[0][14],BS_Count+1) if db_row_to_list[0][14] is not None else (db_row_to_list[0][3],BS_Count)
5 Answers

Not quite. For something this, it would be possible to use an if statement.

if a > 3:
    x = 1
    b = 3
else:
    x = 2
    b = None

If you want everything to become a oneliner, you can use tuple unpacking in Python. What tuple unpacking does is basically take the elements from a tuple and store them as variables, instead of elements of a tuple.

An application of this concept would be something like this:

x, b = (1, 3) if a > 3 else (2, None)

Note that it is a oneliner!

EDIT: To answer your question in the updated context:

You can use the following, shorter code. I think the effect will be the same.

a = 3
b = 7
c = 6
a, b = (8, b+1) if c > 3 else (5, b)
print(a, b)

In your example:

x=1 if a>3 else 2

The conditional expression part is:

1 if a>3 else 2

So, you're assigning the result of that conditional expression to x.

In your second example, this is invalid syntax:

x=1,b=3 if a>3 else 2

That's because it's equivalent to:

(1,b)=3 if a>3 else 2

Or, as a simpler example:

(1,b)=3

This is invalid syntax, because you can't do something like 1 = 3 in Python, which is what that code is trying to do. Although if both elements of the tuple were not literals, you'd get a different error:

(b,a)=3
TypeError: cannot unpack non-iterable int object

So, if you want to do multiple assignments with a conditional expression, you can have the conditional expression return a tuple, and have your left-hand side be a tuple of the two variables you want to assign values to:

x,b=(1, 3) if a>3 else (2, 2)

This is equivalent to:

if a > 3:
    x = 1
    b = 3
else:
    x = 2
    b = 2

Which is what I assume you intended with your original code.

You can use tuples:

>>> a = 4
>>> (x, b) = (1, 3) if a > 3 else (2, 2)
>>> x
1
>>> b
3
>>>

The statement x = 1, b = 3 if a > 3 else 2 is not valid. You can still have a one-liner though:

x, b = 1 if a > 3 else 2, 3 if a > 3 else 2

This sets the value of x to 1 if a > 3 else 2 and b to 3 if a > 3 else 2

For context : This is the actual code >

     if db_row_to_list[0][14] is not None:  
        previousTime=db_row_to_list[0][14]    
        BS_Count+=1  
     else:  
        db_row_to_list[0][3] 

I can do this though : ie. use a function > but is it any better??

     num=3  
     num1=7
     def doIt():
        print("doIt()")
        global num,num1
        num=8
        num1+=1
        return num

     a=6
     num=doIt() if a>3 else 5
     print(num," ",num1)
Related