Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: shortcut conditional expression

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)
like image 771
pythonDerby Avatar asked Jul 26 '26 19:07

pythonDerby


2 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)
like image 192
idontknow Avatar answered Jul 28 '26 09:07

idontknow


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.

like image 24
Random Davis Avatar answered Jul 28 '26 09:07

Random Davis