Python If-Else Statement in One Line - Ternary Operator Explained

Python If-Else Statement in One Line - Ternary Operator Explained

Single-line conditionals in Python? Here’s when to and when NOT to use them

Python isn’t the fastest programming language out there, but boy is it readable and efficient to write. Everyone knows what conditional statements are, but did you know you can write if statements in one line of Python code? As it turns out you can, and you’ll learn all about it today.

After reading, you’ll know everything about Python’s If Else statements in one line. You’ll understand when to use them, and when it’s best to avoid them and stick to conventional conditional statements.

Don’t feel like reading? Watch my video instead:

Want to get hired as a data scientist? Running a data science blog might help:

Can Blogging About Data Science Really Get You Hired as a Data Scientist?


What’s Wrong With the Normal If Statement?

Absolutely nothing. Splitting conditional statements into multiple lines of code has been a convention for ages. Most programming languages require the usage of curly brackets, and hence the single line if statements are not an option. Other languages allow writing only simple conditionals in a single line.

And then there’s Python. Before diving into If Else statements in one line, let’s first make a short recap on regular conditionals.

For example, you can check if a condition is true with the following syntax:

age = 16

if age < 18:
    print('Go home.')

The variable age is less than 18 in this case, so Go home. is printed to the console. You can spice things up by adding an else condition that gets evaluated if the first condition is False:

age = 19

if age < 18:
    print('Go home.')
else:
    print('Welcome!')

This time age is greater than 18, so Welcome! gets printed to the console. Finally, you can add one or multiple elif conditions. These are used to capture the in-between cases. For example, you can print something entirely different if age is between 16 (included) and 18 (excluded):

age = 17

if age < 16:
    print('Go home.')
elif 16 <= age < 18:
    print('Not sure...')
else:
    print('Welcome!')

The variable age is 17, which means the condition under elif is True, hence Not sure... is printed to the console.

Pretty basic stuff, so we naturally don’t want to spend so many lines of code writing it. As it turns out, you can use the ternary operator in Python to evaluate conditions in a single line.

Ternary Operator in Python

A ternary operator exists in some programming languages, and it allows you to shorten a simple If-Else block. It takes in 3 or more operands:

  1. Value if true - A value that’s returned if the condition evaluates to True.
  2. Condition - A boolean condition that has to be satisfied to return value if true.
  3. Value if false - A value that’s returned if the condition evaluates to False. In code, it would look like this:
a if condition else b

You can even write else-if logic in Python’s ternary operator. In that case, the syntax changes slightly:

a if condition1 else b if condition2 else c

I have to admit - it looks a bit abstract when written like this. You’ll see plenty of practical examples starting from the next section.

One-Line If Statement (Without Else)

A single-line if statement just means you’re deleting the new line and indentation. You’re still writing the same code, with the only twist being that it takes one line instead of two.

Note: One-line if statement is only possible if there’s a single line of code following the condition. In any other case, wrap the code that will be executed inside a function.

Here’s how to transform our two-line if statement to a single-line conditional:

age = 17

if age < 18: print('Go home.')

As before, age is less than 18 so Go home. gets printed.

What if you want to print three lines instead of one? As said before, the best practice is to wrap the code inside a function:

def print_stuff():
    print('Go home.')
    print('.......')
    print('Now!')
    
age = 17    
    
if age < 18: print_stuff()

One-line if statements in Python are pretty boring. The real time and space saving benefit happens when you add an else condition.

You’ll benefit the most from one-line if statements if you add one or multiple else conditions.

One-Line If-Else Statement

Now we can fully leverage the power of Python’s ternary operator. The code snippet below stores Go home. to a new variable outcome if the age is less than 18 or Welcome! otherwise:

age = 19

outcome = 'Go home.' if age < 18 else 'Welcome!'
print(outcome)

As you would guess, Welcome! is printed to the console as age is set to 19. If you want to print multiple lines or handle more complex logic, wrap everything you want to be executed into a function - just as before.

You now have a clear picture of how the ternary operator works on a simple one-line if-else statement. We can add complexity by adding more conditions to the operator.

One-Line If-Elif-Else Statement

Always be careful when writing multiple conditions in a single line of code. The logic will still work if the line is 500 characters long, but it’s near impossible to read and maintain it.

You should be fine with two conditions in one line, as the code is still easy to read. The following example prints Go home. if age is below 16, Not Sure... if age is between 16 (included) and 18 (excluded), and Welcome otherwise:

age = 17

outcome = 'Go home.' if age < 16 else 'Not sure...' if 16 <= age < 18 else 'Welcome'
outcome

You’ll see Not sure... printed to the console, since age is set to 17. What previously took us six lines of code now only takes one. Neat improvement, and the code is still easy to read and maintain.

What else can you do with one-line if statements? Well, a lot. We’ll explore single-line conditionals for list operations next.

Example: One-Line Conditionals for List Operations

Applying some logic to a list involves applying the logic to every list item, and hence iterating over the entire list. Before even thinking about a real-world example, let’s see how you can write a conditional statement for every list item in a single line of code.

How to Write IF and FOR in One Line

You’ll need to make two changes to the ternary operator:

Surround the entire line of code with brackets [] Append the list iteration code (for element in array) after the final else Here’s how the generic syntax looks like:

[a if condition else b for element in array]

It’s not that hard, but let’s drive the point home with an example. The following code snippet prints + if the current number of a range is greater than 5 and - otherwise. The numbers range from 1 to 10 (included):

['+' if i > 5 else '-' for i in range(1, 11)]
Image 1 - If and For in a single line in Python (image by author)

Image 1 - If and For in a single line in Python (image by author)

Let’s now go over an additional real-world example.

Example: Did Student Pass the Exam?

To start, we’ll declare a list of students. Each student is a Python dictionary object with two keys: name and test score:

students = [
    {'name': 'Bob', 'score': 42},
    {'name': 'Kelly', 'score': 58},
    {'name': 'Austin', 'score': 99},
    {'name': 'Kyle', 'score': 31}
]

We want to print that the student has passed the exam if the score is 50 points or above. If the score was below 50 points, we want to print that the student has failed the exam.

In traditional Python syntax, we would manually iterate over each student in the list and check if the score is greater than 50:

outcomes = []

for student in students:
    if student['score'] > 50:
        outcomes.append(f"{student['name']} passed the exam!")
    else:
        outcomes.append(f"{student['name']} failed the exam!")
        
print(outcomes)
Image 2 - List iteration with traditional Python syntax (image by author)

Image 2 - List iteration with traditional Python syntax (image by author)

The code works, but we need 5 lines to make a simple check and store the results. You can use your newly-acquired knowledge to reduce the amount of code to a single line:

outcomes = [f"{student['name']} passed the exam!" if student['score'] > 50 else f"{student['name']} failed the exam!" for student in students]
print(outcomes)
Image 3 - One-line conditional and a loop with Python (image by author)

Image 3 - One-line conditional and a loop with Python (image by author)

The results are identical, but we have a much shorter and neater code. It’s just on the boundary of being unreadable, which is often a tradeoff with ternary operators and single-line loops. You often can’t have both readable code and short Python scripts.

Just because you can write a conditional in one line, it doesn’t mean you should. Readability is a priority. Let’s see in which cases you’re better off with traditional if statements.

Be Careful With One-Line Conditionals

Just because code takes less vertical space doesn’t mean it’s easier to read. Now you’ll see the perfect example of that claim.

The below snippet checks a condition for every possible grade (1-5) with a final else condition capturing invalid input. The conditions take 12 lines of code to write, but the entire snippet is extremely readable:

grade = 1

if grade == 1:
    print('Grade = 1')
elif grade == 2:
    print('Grade = 2')
elif grade == 3:
    print('Grade = 3')
elif grade == 4:
    print('Grade = 4')
elif grade == 5:
    print('Grade = 5')
else:
    print('Impossible grade!')

As expected, you’ll see Grade = 1 printed to the console, but that’s not what we’re interested in. We want to translate the above snippet into a one-line if-else statement with the ternary operator.

It’s possible - but the end result is messy and unreadable:

grade = 1

outcome = 'Grade = 1' if grade == 1 else 'Grade = 2' if grade == 2 else 'Grade = 3' if grade == 3 else 'Grade = 4' if grade == 4 else 'Grade = 5' if grade == 5 else 'Impossible grade'
print(outcome)

This is an example of an extreme case where you have multiple conditions you have to evaluate. It’s better to stick with the traditional if statements, even though they take more vertical space.

Take home point: A ternary operator with more than two conditions is just a nightmare to write and debug.


Conclusion

And there you have it - everything you need to know about one-line if-else statements in Python. You’ve learned all there is about the ternary operator, and how to write conditionals starting with a single if to five conditions in between.

Remember to keep your code simple. The code that’s easier to read and maintain is a better-written code at the end of the day. Just because you can cram everything into a single line, doesn’t mean you should. You’ll regret it as soon as you need to make some changes.

An even cleaner way to write long conditionals is by using structural pattern matching - a new feature introduced in Python 3.10. It brings the beloved switch statement to Python for extra readability and speed of development.

What do you guys think of one-line if-else statements in Python? Do you use them regularly or have you switched to structural pattern matching? Let me know in the comment section below.