Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 6

 Tutorialskeyboard_arrow_down

 Studentkeyboard_arrow_down
 Courses
 Jobskeyboard_arrow_down

Sign In
 Sign In
 Home
 Courses
 Algorithmskeyboard_arrow_down
 Data Structureskeyboard_arrow_down
 Languageskeyboard_arrow_down
 Interview Cornerkeyboard_arrow_down
 GATEkeyboard_arrow_down
 CS Subjectskeyboard_arrow_down
 Studentkeyboard_arrow_down
 Jobskeyboard_arrow_down
 GBlog
 Puzzles
 What's New ?
Introductionexpand_more
Input/Outputexpand_more
Operatorsexpand_more

o Python Operators
o Ternary Operator in Python
o Division Operators in Python
o Operator Overloading in Python
o Any All in Python
o Operator Functions in Python | Set 1
o Operator Functions in Python | Set 2
o Difference between == and is operator in Python
o Python Membership and Identity Operators
Data Typesexpand_more
Control Flowexpand_more
Functionsexpand_more
Python OOPexpand_more
Exception Handlingexpand_more
File handlingexpand_more
Python Regexexpand_more
Python Collectionsexpand_more
Python NumPyexpand_more
Python Pandasexpand_more
Python Djangoexpand_more
Python JSONexpand_more
Python CSVexpand_more
Python MySQLexpand_more
Python MongoDBexpand_more
Python OpenCVexpand_more
Python Seleniumexpand_more
Python Tkinterexpand_more
Python Kivyexpand_more
Python Examples and Quizexpand_more
Ternary Operator in Python
Last Updated: 24-04-2020
Ternary operators also known as conditional expressions are operators that evaluate something based on a
condition being true or false. It was added to Python in version 2.5.
It simply allows to test a condition in a single line replacing the multiline if-else making the code compact.
Syntax :
[on_true] if [expression] else [on_false]
1. Simple Method to use ternary operator:
filter_none
edit
play_arrow
brightness_4
# Program to demonstrate conditional operator
a, b = 10, 20
  
# Copy value of a in min if a < b else copy b
min = a if a < b else b
  
print(min)
Output:
10
2. Direct Method by using tuples, Dictionary and lambda
filter_none
edit
play_arrow
brightness_4
# Python program to demonstrate ternary operator
a, b = 10, 20
  
# Use tuple for selecting an item
# (if_test_false,if_test_true)[test]
print( (b, a) [a < b] )
  
# Use Dictionary for selecting an item
print({True: a, False: b} [a < b])
  
# lamda is more efficient than above two methods
# because in lambda  we are assure that
# only one expression will be evaluated unlike in
# tuple and Dictionary
print((lambda: b, lambda: a)[a < b]())
Output:
10
10
10
3. Ternary operator can be written as nested if-else:
filter_none
edit
play_arrow
brightness_4
# Python program to demonstrate nested ternary operator
a, b = 10, 20
  
print ("Both a and b are equal" if a == b else "a is greater than b"
        if a > b else "b is greater than a")
Above approach can be written as:
filter_none
edit
play_arrow
brightness_4
# Python program to demonstrate nested ternary operator
a, b = 10, 20
  
if a != b:
    if a > b:
        print("a is greater than b")
    else:
        print("b is greater than a")
else:
    print("Both a and b are equal")
Output: b is greater than a

Important Points:
 First the given condition is evaluated (a < b), then either a or b is returned based on the Boolean
value returned by the condition
 Order of the arguments in the operator is different from other languages like C/C++ (See C/C++
ternary operators).
 Conditional expressions have the lowest priority amongst all Python operations.
Method used prior to 2.5 when ternary operator was not present
In an expression like the one given below , the interpreter checks for the expression if this is true then on_true
is evaluated, else the on_false is evaluated.

Syntax :
'''When condition becomes true, expression [on_false]
is not executed and value of "True and [on_true]"
is returned. Else value of "False or [on_false]"
is returned.
Note that "True and x" is equal to x.
And "False or x" is equal to x. '''
[expression] and [on_true] or [on_false]
Example :
filter_none
edit
play_arrow
brightness_4
      
# Program to demonstrate conditional operator
a, b = 10, 20
  
# If a is less than b, then a is assigned
# else b is assigned (Note : it doesn't 
# work if a is 0.
min = a < b and a or b
  
print(min)
Output:
10
Note : The only drawback of this method is that on_true must not be zero or False. If this happens on_false
will be evaluated always. The reason for that is if expression is true, the interpreter will check for the on_true,
if that will be zero or false, that will force the interpreter to check for on_false to give the final result of whole
expression.
This article is contributed by Mayank Rawat and improved by Shubham Bansal. If you like GeeksforGeeks
and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your
article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and
help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic
discussed above.
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn
the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python
DS Course.

Recommended Posts:
 Benefits of Double Division Operator over Single Division Operator in Python
 Ternary contours Plot using Plotly in Python
 Ternary Search Visualization using Pygame in Python
 How to create a Ternary Overlay using Plotly?
 Ternary Plots in Plotly
 Operator Functions in Python | Set 2
 Operator Functions in Python | Set 1
 Python | Operator.countOf
 Walrus Operator in Python 3.8
 Python | List comprehension vs * operator
 Check if a value exists in a DataFrame using in & not in operator in Python-Pandas
 Concatenate two strings using Operator Overloading in Python
 What is a modulo operator (%) in Python?
 Difference between == and is operator in Python
 Operator Overloading in Python
 Python - Star or Asterisk operator ( * )
 What does the Double Star operator mean in Python?
 Difference between != and is not operator in Python
 Operator Overloading in C++
 Implement *, - and / operations using only + arithmetic operator

Improved By : nsuman35

Article Tags : 
Python

School Programming

thumb_up
22

To-do  Done
2.1
Based on 35 vote(s)
Improve Article
 
 
Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.
Post navigation
Previous
first_page Get() method for dictionaries in Python
Next
last_pagePython String Methods | Set 2 (len, count, center,
ljust, rjust, isalpha, isalnum, isspace & join)

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.

Load Comments

Most popular in Python


 Python map() function
 Adding new column to existing DataFrame in Pandas
 Enumerate() in Python
 Python program to convert a list to string
 Iterate over a list in Python

Most visited in School Programming


 Arrays in C/C++
 C++ Data Types
 Inheritance in C++
 Reverse a string in Java
 C++ Classes and Objects

room5th Floor, A-118,


Sector-136, Noida, Uttar Pradesh - 201305

emailfeedback@geeksforgeeks.org

 Company
 About Us
 Careers
 Privacy Policy
 Contact Us
 Learn
 Algorithms
 Data Structures
 Languages
 CS Subjects
 Video Tutorials
 Practice
 Courses
 Company-wise
 Topic-wise
 How to begin?
 Contribute
 Write an Article
 Write Interview Experience
 Internships
 Videos
@geeksforgeeks , Some rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you
have read and understood our Cookie Policy & Privacy PolicyGot It !

You might also like