**Problem**: How to perform one-line if conditional assignments in Python?

**Example**: Say, you start with the following code.

x = 2 boo = True

You want to set the value of `x`

to `42`

if `boo`

is `True`

, and do nothing otherwise.

Let’s dive into the different ways to accomplish this in Python. We start with an overview:

**Exercise**: Run the code. Are all outputs the same?

Next, you’ll dive into each of those methods and boost your one-liner superpower!

## Method 1: Ternary Operator

The most basic ternary operator `x if c else y`

returns expression `x`

if the Boolean expression `c`

evaluates to `True`

. Otherwise, if the expression `c`

evaluates to `False`

, the ternary operator returns the alternative expression `y`

.

<OnTrue> if <Condition> else <OnFalse>

Operand | Description |
---|---|

<OnTrue> | The return expression of the operator in case the condition evaluates to `True` |

<Condition> | The condition that determines whether to return the <On True> or the <On False> branch. |

<OnFalse> | The return expression of the operator in case the condition evaluates to `False` |

*Operands of the Ternary Operator*

Let’s go back to our example problem! You want to set the value of `x`

to `42`

if `boo`

is `True`

, and do nothing otherwise. Here’s how to do this in a single line:

x = 42 if boo else x

While using the ternary operator works, you may wonder whether it’s possible to avoid the `...else x`

part for clarity of the code? In the next method, you’ll learn how!

If you need to improve your understanding of the ternary operator, watch the following video:

You can also read the related article:

## Method 2: Single-Line If Statement

Like in the previous method, you want to set the value of `x`

to `42`

if `boo`

is `True`

, and do nothing otherwise. But you don’t want to have a redundant else branch. How to do this in Python?

The solution to skip the else part of the ternary operator is surprisingly simple—** use a standard if statement without else branch and write it into a single line of code**:

if boo: x = 42

To learn more about what you can pack into a single line, watch my tutorial video “If-Then-Else in One Line Python”:

## Method 3: Ternary Tuple Syntax Hack

A shorthand form of the ternary operator is the following **tuple syntax**.

**Syntax**: You can use the tuple syntax `(x, y)[c]`

consisting of a tuple `(x, y)`

and a condition `c`

enclosed in a square bracket. Here’s a more intuitive way to represent this tuple syntax.

(<OnFalse>, <OnTrue>)[<Condition>]

Operand | Description |
---|---|

<OnTrue> | The return expression of the operator in case the condition evaluates to `True` |

<Condition> | The condition that determines whether to return the <On True> or the <On False> branch. |

<OnFalse> | The return expression of the operator in case the condition evaluates to `False` |

*Tuple Syntax of the Ternary Operator*

In fact, the order of the `<OnFalse>`

and `<OnTrue>`

operands is just flipped when compared to the basic ternary operator. First, you have the branch that’s returned if the condition does NOT hold. Second, you run the branch that’s returned if the condition holds.

x = (x, 42)[boo]

Clever! The condition `boo`

holds so the return value passed into the `x`

variable is the `<OnTrue>`

branch `42`

.

Don’t worry if this confuses you—you’re not alone. You can clarify the tuple syntax once and for all by studying my detailed blog article.

**Related Article**: Python Ternary — Tuple Syntax Hack

## Python One-Liners Book: Master the Single Line First!

**Python programmers will improve their computer science skills with these useful one-liners.**

*Python One-Liners* will teach you how to read and write “one-liners”: ** concise statements of useful functionality packed into a single line of code. **You’ll learn how to systematically unpack and understand any line of Python code, and write eloquent, powerfully compressed Python like an expert.

The book’s five chapters cover (1) tips and tricks, (2) regular expressions, (3) machine learning, (4) core data science topics, and (5) useful algorithms.

Detailed explanations of one-liners introduce ** key computer science concepts **and

**. You’ll learn about advanced Python features such as**

*boost your coding and analytical skills**,*

**list comprehension****,**

*slicing***,**

*lambda functions***,**

*regular expressions***and**

*map***functions, and**

*reduce***.**

*slice assignments*You’ll also learn how to:

- Leverage data structures to
**solve real-world problems**, like using Boolean indexing to find cities with above-average pollution - Use
**NumPy basics**such as*array*,*shape*,*axis*,*type*,*broadcasting*,*advanced indexing*,*slicing*,*sorting*,*searching*,*aggregating*, and*statistics* - Calculate basic
**statistics**of multidimensional data arrays and the K-Means algorithms for unsupervised learning - Create more
**advanced regular expressions**using*grouping*and*named groups*,*negative lookaheads*,*escaped characters*,*whitespaces, character sets*(and*negative characters sets*), and*greedy/nongreedy operators* - Understand a wide range of
**computer science topics**, including*anagrams*,*palindromes*,*supersets*,*permutations*,*factorials*,*prime numbers*,*Fibonacci*numbers,*obfuscation*,*searching*, and*algorithmic sorting*

By the end of the book, you’ll know how to ** write Python at its most refined**, and create concise, beautiful pieces of “Python art” in merely a single line.

*Get your Python One-Liners on Amazon!!*

While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.

To help students reach higher levels of Python success, he founded the programming education website Finxter.com that has taught exponential skills to millions of coders worldwide. He’s the author of the best-selling programming books Python One-Liners (NoStarch 2020), The Art of Clean Code (NoStarch 2022), and The Book of Dash (NoStarch 2022). Chris also coauthored the Coffee Break Python series of self-published books. He’s a computer science enthusiast, freelancer, and owner of one of the top 10 largest Python blogs worldwide.

His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here.