Lokasi ngalangkungan proxy:   [ UP ]  
[Ngawartoskeun bug]   [Panyetelan cookie]                
Skip to content
No results
  • About AskPython
  • Blog
  • Contact Me
  • Free Online Developer Tools Hub
  • Home
  • Meet the Team
  • Privacy Policy
  • Python
  • Python Course for Beginners Online FREE
  • Python Tutorial – Mega Index
  • Terms and Conditions

🚀 Supercharge your YouTube channel's growth with AI.

Try YTGrowAI Free
  • Home
  • Blog
  • About AskPython
  • Python Course
  • Start Here

Python ternary Operator Examples

  • Pankaj KumarPankaj Kumar
  • September 10, 2019
  • Python Programming
Python ternary Operator Examples

Python doesn’t have a ternary operator. But, it supports writing an if-else statement in such a way that it works as a Python ternary operator.


Why Python doesn’t have a special ternary operator?

Many programming languages have ternary operators. But, their main purpose is to reduce the code size by removing simple if-else blocks. Python improved the if-else statements itself to reduce the code size rather than adding an additional operator.


Python ternary operator implementation

The syntax of mimicking ternary operator in Python is:

[when_true] if [condition] else [when_false]

If the condition is evaluated to True, the when_true value is returned, otherwise when_false is returned.


Python ternary operator Example

Let’s say we have a simple code to check if an integer is odd or even. We are asking the user to enter the number and printing whether it’s odd or even. We will implement it using the if-else block.

x = int(input("Please enter an integer:\n"))

if x % 2 == 0:
    int_type = 'even'
else:
    int_type = 'odd'

print(f'You entered {x} which is an {int_type} integer.')

The whole code snippet has 6 lines, out of which 4 are if-else block. This is a perfect place to use the improved if-else ternary operator support.

x = int(input("Please enter an integer:\n"))

int_type = 'even' if x % 2 == 0 else 'odd'

print(f'You entered {x} which is an {int_type} integer.')
Python Ternary Operator
Python Ternary Operator

Ternary Operator with Tuple

Python tuple also supports the ternary operator. Its syntax is:

(when_false, when_true)[condition]

If the condition is True, the first value is returned. Otherwise, the second value is returned.

Let’s convert the above example to use the ternary operator with a tuple.

x = int(input("Please enter an integer:\n"))

int_type = ('even', 'odd')[x % 2]

print(f'You entered {x} which is an {int_type} integer.')

Which is Better? if-else or tuple?

When we use the if-else based ternary operator, the condition is evaluated first.

In the tuple based implementation, the tuple elements are evaluated first and then the condition.

So, if there is some processing involved in generating both the possible values, the if-else is more efficient.

Let’s understand this with a simple code snippet.

def foo(s):
    print(f'foo called with parameter {s}')
    return s


flag = True

if flag:
    result = foo('if')
else:
    result = foo('else')

result = foo('ternary-if') if flag else foo('ternary-else')

result = (foo('tuple-true'), foo('tuple-false'))[flag]

print('Done')

Output:

foo called with parameter if
foo called with parameter ternary-if
foo called with parameter tuple-true
foo called with parameter tuple-false
Done

It’s clear from the output that the if-else based ternary operator implementation is better to use.


References:

  • StackOverflow Question
Pankaj Kumar
Pankaj Kumar

I have been working on Python programming for more than 12 years. At AskPython, I share my learning on Python with other fellow developers.

Articles: 264
Understanding Python self Variable with Examples
Previous Post Understanding Python self Variable with Examples
Next Post Python // operator - Floor Based Division
Python // operator – Floor Based Division

Related Posts

What Does %s Mean in Python String Formatting?

What Does %s Mean in a Python Format String?

  • November 30, 2026
Python Convert String to List

Python Convert String to List: Choose the Right Method

  • November 29, 2026
Translate String Python

Translate String Python

  • November 29, 2026

Partner Websites

  • GoLangDocs
  • LinuxForDevices
  • CodeForGeek

Popular Categories

  • Python Programming
  • Python Modules
  • OOPS in Python
  • Python Programming Examples
  • Strings in Python

Hall of Fame

  • Python Programming
  • OOPS in Python
  • Creating Python Modules
  • Args and Kwargs in Python
  • Python Dictionary (Dict) Tutorial
  • Python List – 15 Things You MUST Know
  • Python Set – Things You MUST Know
  • Python String Functions: Methods by Task

Important Links

  • Home
  • Python Course
  • Start Here
  • Blog
  • About AskPython
Latest posts
  • np.linalg.eig: Eigenvalues and Eigenvectors
  • What Does %s Mean in a Python Format String?
  • How to Use np.sin() in NumPy
  • cv2.imread: Load Images with OpenCV
  • pd.read_json: Read JSON Into a DataFrame

Copyright © 2026 - AskPython. All rights reserved.