Ternary operators in Python

Ternary operators in Python

Condense if-else statements to one-liners easier to read

What is a ternary operator in Python?🐍

A ternary operator is an expression used to write conditional statements on one line in Python, offering a more concise alternative to if-else statements.

Anatomy of a ternary operator 🧬

Each ternary operator consists of three components:

  1. A condition (🎭)

  2. A value when the condition is true (👍)

  3. A value when the condition is false (👎)

Benefits of ternary operators

Ternary operators are

  • Efficient 🚀- reduces the need for multiple lines of code

  • Readable 📖- simplifies complex operations into more manageable ones

  • Easy to debug & maintain 🔧- with a modular structure, it’s easy to find the bugs and defects in the code and fix them

Examples 📚

Let’s explore some code examples to see how ternary operators are used:

Dataset for demo📈

We’ll use a dataset containing flight details that include the destinations, durations and statuses of flights.

Each record represents a flight:

flights = [
    {"destination": "France", "duration": 120, "status": "On Time"},
    {"destination": "Nigeria", "duration": 360, "status": "On Time"},
    {"destination": "Japan", "duration": 480, "status": "Delayed"},
    {"destination": "Ghana", "duration": 300, "status": "On Time"},
    {"destination": "China", "duration": 510, "status": "Delayed"},
    {"destination": "Dubai", "duration": 390, "status": "On Time"},
    {"destination": "USA", "duration": 430, "status": "Delayed"},
    {"destination": "Spain", "duration": 140, "status": "On Time"}
]

Example 1: Readability 📖

Problem 🛑

for flight in flights:
    if flight['status'] == 'On Time':
        print(f"Flight to {flight['destination']} is on schedule ")
    else:
        print(f"Flight to {flight['destination']} is delayed... ")

Output:

Flight to France is on schedule
Flight to Nigeria is on schedule
Flight to Japan is delayed...
Flight to Ghana is on schedule
Flight to China is delayed...
Flight to Dubai is on schedule
Flight to USA is delayed...
Flight to Spain is on schedule

Although this if-else statement is clear, it is verbose (more words than needed are used) for a simple status check.

The repeated phrase “Flight to xxx is xxx” can be condensed using a ternary operator:

Solution🟢

for flight in flights:
    status_report = 'on schedule' if flight['status'] == 'On Time' else 'delayed...'
    print(f"Flight to {flight['destination']} is {status_report} ")

Output:

Flight to France is on schedule
Flight to Nigeria is on schedule
Flight to Japan is delayed...
Flight to Ghana is on schedule
Flight to China is delayed...
Flight to Dubai is on schedule
Flight to USA is delayed...
Flight to Spain is on schedule

This version returns the same output by using fewer lines of code and eliminating the repetitive statements, which can now be understood at a glance i.e. more concise, less repetitive, and therefore enhancing the code’s readability.

Simpler code is often more readable.

Example 2: Efficiency 🚀

Problem 🛑

for flight in flights:
    status = ''
    if flight['duration'] < 180:
        status = 'short-haul'
    elif flight['duration'] < 360:
        status = 'medium-haul'
    else:
        status = 'long-haul'
    print(f"Flight to {flight['destination']} is a {status} flight.")

Output:

Flight to France is a short-haul flight.
Flight to Nigeria is a long-haul flight.
Flight to Japan is a long-haul flight.
Flight to Ghana is a medium-haul flight.
Flight to China is a long-haul flight.
Flight to Dubai is a long-haul flight.
Flight to USA is a long-haul flight.
Flight to Spain is a short-haul flight.

The above code snippet works correctly and the data returned is accurate, however, it achieves this through multiple if-else statements, which is lengthier and less efficient.

This requires the reader the check each line sequentially, which could be time-consuming if we’re dealing with larger code bases (which is what we get in the real world).

Solution 🟢

for flight in flights:
    flight_category = ('short-haul' if flight['duration'] < 180 else
                        'medium-haul' if flight['duration'] < 360 else
                        'long-haul')
    print(f"Flight to {flight['destination']} is a {flight_category} flight.")

Output:

Flight to France is a short-haul flight.
Flight to Nigeria is a long-haul flight.
Flight to Japan is a long-haul flight.
Flight to Ghana is a medium-haul flight.
Flight to China is a long-haul flight.
Flight to Dubai is a long-haul flight.
Flight to USA is a long-haul flight.
Flight to Spain is a short-haul flight.

Using the ternary operator provides a more compact way to express the same logic. This allows a more concise expression of the conditional logics to fit on the same line, making the code more elegant to read.

When you deal with larger datasets, having this approach leads to less cognitive load for understanding each line of code you navigate through i.e. less time and mental energy to understand what’s going on in the script.

Example 3: Debugging + Maintenance 🔧

Problem 🛑

for flight in flights:
    print(f"Flight to {flight['destination']} is {'on schedule' if flight['status'] == 'On Time' else 'delayed...'}")

Output:

Flight to France is on schedule
Flight to Nigeria is on schedule
Flight to Japan is delayed...
Flight to Ghana is on schedule
Flight to China is delayed...
Flight to Dubai is on schedule
Flight to USA is delayed...
Flight to Spain is on schedule

Yes, this is concise and makes use of the ternary operator, but this can be difficult to troubleshoot because of how compact the one-line code is.

If there are too many items squeezed into one line of code, the code becomes harder to read and therefore more difficult to debug.

The goal of using ternary operators is to spend less time breaking down code by understanding it quickly. Too many items on one line leads to more cognition used to understand how each piece fits into the structure before knowing where the issues may lie in the code.

Solution 🟢

for flight in flights:
    status_report = 'on schedule' if flight['status'] == 'On Time' else 'delayed...'
    print(f"Flight to {flight['destination']} is {status_report}")

Output:

Flight to France is on schedule
Flight to Nigeria is on schedule
Flight to Japan is delayed...
Flight to Ghana is on schedule
Flight to China is delayed...
Flight to Dubai is on schedule
Flight to USA is delayed...
Flight to Spain is on schedule

Now that the ternary operator has been separated from the print statement, the code suddenly becomes easier to read, and therefore easier to identify any issues and fix them accordingly if they occur.

Pro tips 💡

Here are some guidelines to consider when dealing with ternary operators:

1. Keep it simple 👌

Use ternary operators for simple, straightforward conditions. Avoid nested and complex ternaries at all cost - this will reduce readability significantly.

for flight in flights:
    urgency_level = 'URGENT🚨' if flight['duration'] < 150 else 'NORMAL💚'
    print(f"Flight to {flight['destination']} is classed as '{urgency_level}' due to duration")

Output:

Flight to France is classed as 'URGENT🚨' due to duration
Flight to Nigeria is classed as 'NORMAL💚' due to duration
Flight to Japan is classed as 'NORMAL💚' due to duration
Flight to Ghana is classed as 'NORMAL💚' due to duration
Flight to China is classed as 'NORMAL💚' due to duration
Flight to Dubai is classed as 'NORMAL💚' due to duration
Flight to USA is classed as 'NORMAL💚' due to duration
Flight to Spain is classed as 'URGENT🚨' due to duration
for flight in flights:
    urgency_level = 'URGENT🚨' if flight['duration'] < 120 else 'MODERATE🟠' if flight['duration'] < 240 else 'NORMAL💚'
    print(f'Flight to {flight["destination"]} is {urgency_level} due to duration.')

Output:

Flight to France is MODERATE🟠 due to duration.
Flight to Nigeria is NORMAL💚 due to duration.
Flight to Japan is NORMAL💚 due to duration.
Flight to Ghana is NORMAL💚 due to duration.
Flight to China is NORMAL💚 due to duration.
Flight to Dubai is NORMAL💚 due to duration.
Flight to USA is NORMAL💚 due to duration.
Flight to Spain is MODERATE🟠 due to duration.

2. Use comments for clarity 🗨️

Add comments to break down the logic of the code when ternary operators are used in not-so-obvious conditions and areas.

for flight in flights:
    # Check if the flight is a short international flight
    flight_type = 'short international' if flight['duration'] < 180 and flight['destination'] not in ['USA', 'China'] else 'other'
    print(f'Flight to {flight["destination"]} is classified as {flight_type}.')

3. Prioritize readability over brevity📚

If the ternary operator makes the code less readable, dump it.

There are situations where the traditional if-else statement is better than ternary operators.

3.1. Ternary operator

for flight in flights:
    status = 'check-in' if flight['status'] == 'Delayed' else 'proceed to gate'
    print(f'Passengers for flight to {flight["destination"]} should {status}.')

3.2. If-else statement

for flight in flights:
    if flight['status'] == 'Delayed':
        status = 'check-in'
    else:
        status = 'proceed to gate'
    print(f'Passengers for flight to {flight["destination"]} should {status}.')

Conclusion 🏁

Effective code isn’t always about how many lines of code you can write or how many syntaxes you can squeeze into code blocks; it’s about writing code that is intuitive, accessible and functional.

Aim to write code that makes it easy for others to interact with, as this demonstrates empathy and thoughtfulness towards your audience.

This approach not only reflects real technical expertise but also encourages colleagues, developers and other enthusiasts to collaborate once they spend less time and cognition coming up to speed with your coding intentions.


For deeper dives and insights into these data engineering topics with clear and simple code examples on how they are applied in the real world, subscribe to my newsletter below where you can also forward any questions you have privately and I will be happy to answer them for free:

If you enjoyed this article, I have better ones coming soon - subscribe to join over 1k+ members to access it first!


Need advice or have thoughts to share? I’m just a message away:

LinkedIn | Twitter | Email | TikTok