One way to improve the concision of your Python code is by using the ternary operator, a handy tool that allows you to condense an if-else statement into a single line of code.
Let us jump straight into it.
Imagine that you have the following comparison:
x = 5
y = 10
if x > y:
result = x
else:
result = y
You can then write it in a single line:
result = x if x > y else y
This is similar to how you would do in other programming languages using ?
and :
, for example in JavaScript:
let x = 5;
let y = 10;
// Using an if-else statement
let result;
if (x > y) {
result = x;
} else {
result = y;
}
// Using the ternary operator
result = x > y ? x : y;
That’s basically it.
I hope you find this useful.