TutorialsTonight Logo

Python Conditional Assignment

When you want to assign a value to a variable based on some condition, like if the condition is true then assign a value to the variable, else assign some other value to the variable, then you can use the conditional assignment operator.

In this tutorial, we will look at different ways to assign values to a variable based on some condition.

1. Using Ternary Operator

The ternary operator is very special operator in Python, it is used to assign a value to a variable based on some condition.

It goes like this:

Here, the value of variable will be value_if_true if the condition is true, else it will be value_if_false .

Let's see a code snippet to understand it better.

You can see we have conditionally assigned a value to variable c based on the condition a > b .

2. Using if-else statement

if-else statements are the core part of any programming language, they are used to execute a block of code based on some condition.

Using an if-else statement, we can assign a value to a variable based on the condition we provide.

Here is an example of replacing the above code snippet with the if-else statement.

3. Using Logical Short Circuit Evaluation

Logical short circuit evaluation is another way using which you can assign a value to a variable conditionally.

The format of logical short circuit evaluation is:

It looks similar to ternary operator, but it is not. Here the condition and value_if_true performs logical AND operation, if both are true then the value of variable will be value_if_true , or else it will be value_if_false .

Let's see an example:

But if we make condition True but value_if_true False (or 0 or None), then the value of variable will be value_if_false .

So, you can see that the value of c is 20 even though the condition a < b is True .

So, you should be careful while using logical short circuit evaluation.

While working with lists , we often need to check if a list is empty or not, and if it is empty then we need to assign some default value to it.

Let's see how we can do it using conditional assignment.

Here, we have assigned a default value to my_list if it is empty.

Assign a value to a variable conditionally based on the presence of an element in a list.

Now you know 3 different ways to assign a value to a variable conditionally. Any of these methods can be used to assign a value when there is a condition.

The cleanest and fastest way to conditional value assignment is the ternary operator .

if-else statement is recommended to use when you have to execute a block of code based on some condition.

Happy coding! 😊

Rolex Pearlmaster Replica

One line if statement in Python (ternary conditional operator)

In the real world, there are specific classifications and conditions on every action that occurs around us. A twelve-year-old person is a kid, whereas a thirteen-year-old person is a teenager. If the weather is pleasant, you can make plans for an outing. But if it isn’t, you will have to cancel your plans. These conditions control the coding world as well. You will encounter various coding problems where you will have to print the output based on some conditions.

Luckily, Python has a straightforward command and syntax to solve such kinds of problems. These are called conditional statements. So let’s begin our discussion on conditional statements, their syntax, and their applications.

Basic if Statement (Ternary Operator) 

Many programming languages have a ternary operator , which defines a conditional expression. The most common usage is to make a terse, simple dependent assignment statement. In other words, it offers a one-line code to evaluate the first expression if the condition is true; otherwise, it considers the second expression. Programming languages derived from C usually have the following syntax:

Basic if Statement

The Python BDFL (creator of Python, Guido van Rossum) rejected it as non-Pythonic since it is hard to understand for people not used to C. Moreover, the colon already has many uses in Python. So, when PEP 308 was approved, Python finally received its shortcut conditional expression:

if else

It first evaluates the condition; if it returns True , the compiler will consider expression1 to give the result, otherwise expression2 . Evaluation is lazy, so only one expression will be executed.

Let's take a look at this example:

Conditions 1

Here we have defined the age variable whose value is fifteen. Now we use the if-else command to print if the kid is an adult or not. The condition for being an adult is that the person’s age should be eighteen or greater than that. We have mentioned this condition in the if-else command. Now let’s see what the output is:

Conditions 2

As we can see, we have obtained the output as “kid” based on the value of the age variable.

We can chain the ternary operators as well:

print 1

Here we have incorporated multiple conditions. This form is the chained form of ternary operators. Let’s check the output:

print 2

This command is the same as the program given below : 

if else statement

The compiler evaluates conditions from left to right, which is easy to double-check with something like the pprint module:

pprint module

Alternatives To The Ternary Operator

For Python versions lower than 2.5, programmers developed several tricks that somehow emulate the behavior of the ternary conditional operator. They are generally discouraged, but it's good to know how they work: 

ternary conditional operator 1

These are various ways to impose conditions in your code :

ternary conditional operator 2

We can see that for various inputs, the same output is obtained for the exact value of the variable.

The problem of such an approach is that both expressions will be evaluated no matter what the condition is. As a workaround, lambdas can help:

print age 1

We obtain the output as follows :

print age 2

Another approach is using 'and' or 'or' statements:

print age 3

Yes, most of the workarounds look ugly. Nevertheless, there are situations when it's better to use 'and' or 'or' logic than the ternary operator. For example, when your condition is the same as one of the expressions, you probably want to avoid evaluating it twice:

void evaluating it twice

Indentations And Blocks

Python is very careful of the syntax of programming statements. We have to maintain proper indentation and blocks while we write composite statements like if-else . The correct indentation syntax of the if-else statement is given as follows:

syntax of programming statements

The statements under 'if' are considered a part of one 'block.' The other statements are not part of the if block and are not considered when statements of 'if' are evaluated.

Python will automatically change the text color if you deviate from this indentation and display an error when you run your code. Let's take an example where we intentionally differ from the proper indentation:

IndentationError 1

We can see here that Python delivers an error message as: "Expected an indented block ."

IndentationError 2

Also, note the color of 'print' in line 3. All the other text is green, while 'print' has the color red. The color variation happens because of the abrupt indentation of 'print.'

Now let us correct the indentation :

print in line

When we have maintained the indentation of Python, we get the output hassle-free.

The else And elif Clauses

Suppose your ‘ if ’ condition is false and you have an alternative statement ready for execution. Then you can easily use the else clause. Now, suppose you have multiple if conditions and an alternative for each one. Then, you can use the elif clause and specify any number of situations. Now let us take an example for each case :

Use of else clause:

The syntax of the   if-else statement is straightforward and has been used multiple times in this tutorial. Let us take a fundamental problem: There is a football team selection. The most critical condition for a candidate's eligibility is that he should be seventeen years or older. If his age is greater than or equal to seventeen, the output will be " You are eligible." If the boy is younger than seventeen years of age, the result will be " Sorry. You are not eligible."

Now let’s look at the code for this problem :

int input 1

Let’s run this code and see what the output is :

int input 2

The program first asks for the user input of age. We first enter the age as sixteen.

int input 3

Now let us enter the age as eighteen and observe the output.

int input 4

Thus we can see that the code assesses the input entered("age") and checks the value against the if-else conditions. If the condition is true, the compiler considers the statement under 'if ' and other statements are ignored. If the condition is false, the compiler executes the statement under 'else ,' and all the other statements are ignored.

Use of elif clause :

We use this clause when we have multiple conditions to check before printing the output. The word elif is compact for ‘ else-if .' When we use the elif clause, the else clause is optional. But if we want to use else clause, there has to be only one clause and that too at the end of the program.

Let us take a problem. We ask the user to enter a number between one and seven, and we display the corresponding weekday name. Let's look at the program for this problem.

int input 5

The above-given code has elif as well as else clause.

Now let’s check the output:

int input 6

The program first asks for user input of a number. Let’s enter four.

int input 7

Now, let's check the output for the input value twelve.

int input 8

Thus, the code works for any user-entered input value.

Conditions dominate every aspect of our real-life situations. To simulate these real-life conditions properly in our virtual world of coding, we, the programmers, need a good grasp on the control statements like if-else . We hope that this article helped you in understanding conditional statements and their syntax in Python. The various problems discussed in this article will help you understand the fundamental concepts of if-else statements and their applications.

About The Author

Anton Caceres

Anton Caceres

  • Python Tips and Tricks

Signup for new content

Thank you for joining our mailing list!

Latest Articles

  • Five Key Applications of Artificial Intelligence and Machine Learning in Finance and Python's Impact on Them
  • Essential System Administrator Tools: Script Automation - Bash, Python and PowerShell
  • The Benefits of Engaging in Python Projects for Beginners
  • Understanding Web App Development: A Beginner's Guide
  • Discover How to Get FL Studio for Free and Start Creating Music Today
  • Data structures
  • installation
  • python function
  • pandas installation
  • Zen of Python
  • concatenation
  • Echo Client
  • NumPy Pad()
  • install python
  • how to install pandas
  • Philosophy of Programming
  • concat() function
  • Socket State
  • Python YAML
  • remove a node
  • function scope
  • Tuple in Python
  • pandas groupby
  • socket programming
  • Python Modulo
  • Dictionary Update()
  • datastructure
  • bubble sort
  • find a node
  • calling function
  • GroupBy method
  • Np.Arange()
  • Modulo Operator
  • Python Or Operator
  • Python salaries
  • pyenv global
  • NumPy arrays
  • insertion sort
  • in place reversal
  • learn python
  • python packages
  • zeros() function
  • Scikit Learn
  • HTML Parser
  • circular queue
  • effiiciency
  • python maps
  • Num Py Zeros
  • Python Lists
  • HTML Extraction
  • selection sort
  • Programming
  • install python on windows
  • reverse string
  • python Code Editors
  • pandas.reset_index
  • Infinite Numbers in Python
  • Python Readlines()
  • Programming language
  • remove python
  • concatenate string
  • Code Editors
  • reset_index()
  • Train Test Split
  • Local Testing Server
  • Python Input
  • priority queue
  • web development
  • uninstall python
  • python string
  • code interface
  • round numbers
  • train_test_split()
  • Flask module
  • Linked List
  • machine learning
  • compare string
  • pandas dataframes
  • arange() method
  • Singly Linked List
  • python scripts
  • learning python
  • python bugs
  • ZipFunction
  • plus equals
  • np.linspace
  • SQLAlchemy advance
  • Data Structure
  • csv in python
  • logging in python
  • Python Counter
  • python subprocess
  • numpy module
  • Python code generators
  • python tutorial
  • csv file python
  • python logging
  • Counter class
  • Python assert
  • numbers_list
  • binary search
  • Insert Node
  • Python tips
  • python dictionary
  • Python's Built-in CSV Library
  • logging APIs
  • Constructing Counters
  • Matplotlib Plotting
  • any() Function
  • linear search
  • Python tools
  • python update
  • logging module
  • Concatenate Data Frames
  • python comments
  • Recursion Limit
  • Subscription

Python Ternary: How to Use It and Why It’s Useful (with Examples)

What is a python ternary operator, and when is it useful this tutorial will walk you through everything you need to know..

The Python ternary operator (or conditional operator ), tests if a condition is true or false and, depending on the outcome, returns the corresponding value — all in just one line of code. In other words, it's a compact alternative to the common multiline if-else control flow statements in situations when we only need to "switch" between two values. The ternary operator was introduced in Python 2.5.

The syntax consists of three operands, hence the name "ternary":

Here are these operands:

  • condition — a Boolean expression to test for true or false
  • a — the value that will be returned if the condition is evaluated to be true
  • b — the value that will be returned if the condition is evaluated to be false

The equivalent of a common if-else statement, in this case, would be the following:

Let's look at a simple example:

While the ternary operator is a way of re-writing a classic if-else block, in a certain sense, it behaves like a function since it returns a value. Indeed, we can assign the result of this operation to a variable:

my_var = a if condition else b

For example:

Before we had the ternary operator, instead of a if condition else b , we would use condition and a or b . For example, instead of running the following . . .

. . . we would run this:

However, if the value of a in the syntax condition and a or b evaluates to False (e.g., if a is equal to 0 , or None , or False ), we would receive inaccurate results. The example of a ternary operator below looks logically controversial (we want to return False if 2 > 1; otherwise, we want to return True ) but it is technically correct since it's up to us to decide which value to return if the condition evaluates to True — and which value to return if the condition evaluates to False . In this case, we expect False , and we got it:

Using the "old-style" syntax instead of the ternary operator for the same purpose, we would still expect False . However, we received an unexpected result:

To avoid such issues, it's always better to use the ternary operator in similar situations.

Limitations of Python Ternary Operator

Note that each operand of the Python ternary operator is an expression , not a statement , meaning that we can't use assignment statements inside any of them. Otherwise, the program throws an error:

If we need to use statements, we have to write a full if-else block rather than the ternary operator:

Another limitation of the Python ternary operator is that we shouldn't use it for testing multiple expressions (i.e., the if-else blocks with more than two cases). Technically, we still can do so. For example, take the following piece of code:

We can rewrite this code using nested ternary operators :

( Side note: In the above piece of code, we omitted the print() statement since the Python ternary operator always returns a value.)

While the second piece of code looks more compact than the first one, it's also much less readable. To avoid readability issues, we should opt to use the Python ternary operator only when we have simple if-else statements.

How to Use a Python Ternary Operator

Now, we'll discuss various ways of applying the Python ternary operator. Let's say we want to check if the water at a certain temperature is boiling or not. At standard atmospheric pressure, water boils at 100 degrees Celsius. Suppose that we want to know if the water in our kettle is boiling given that its temperature reaches 90 degrees Celsius. In this case, we can simply use the if-else block:

We can re-write this piece of code using a simple Python ternary operator:

( Side note: above, we omitted the print() statement since the Python ternary operator always returns a value.)

The syntax for both pieces of code above is already familiar. However, there are some other ways to implement the Python ternary operator that we haven't considered yet.

Using Tuples

The first way to re-organize the Python ternary operator is by writing its tupled form. If the standard syntax for the Python ternary operator is a if condition else b , here we would re-write it as (b, a)[condition] , like this:

In the syntax above, the first item of the tuple is the value that will be returned if the condition evaluates to False (since False==0 ), while the second is the value that will be returned if the condition evaluates to True (since True==1 ).

This way of using the Python ternary operator isn't popular compared to its common syntax because, in this case, both elements of the tuple are evaluated since the program first creates the tuple and only then checks the index. In addition, it can be counterintuitive to identify where to place the true value and where to place the false value.

Using Dictionaries

Instead of tuples, we can also use Python dictionaries, like this:

Now, we don't have the issue of differentiating between the true and false values. However, as with the previous case, both expressions are evaluated before returning the right one.

Using Lambdas

Finally, the last way of implementing the Python ternary operator is by applying Lambda functions. To do so, we should re-write the initial syntax a if condition else b in the following form: (lambda: b, lambda: a)[condition]()

Note that in this case, we can become confused about where to put the true and false values. However, the advantage of this approach over the previous two is that it performs more efficiently because only one expression is evaluated.

Let's sum up what we learned in this tutorial about the Python ternary operator:

  • How the Python ternary operator works
  • When its preferable to a common if-else block
  • The syntax of the Python ternary operator
  • The equivalent of the Python ternary operator written in a common if-else block
  • The old version of the Python ternary operator and its problems
  • The limitations of the Python ternary operator
  • Nested Python ternary operators and their effect on code readability
  • How to apply the Python ternary operator using tuples, dictionaries, and Lambda functions — including the pros and cons of each method

More learning resources

How to use python counters in 2023 (w/ 23 code examples), python if else tutorial: control the flow of your code.

Learn data skills 10x faster

Headshot

Join 1M+ learners

Enroll for free

  • Data Analyst (Python)
  • Gen AI (Python)
  • Business Analyst (Power BI)
  • Business Analyst (Tableau)
  • Machine Learning
  • Data Analyst (R)

Python One Line Conditional Assignment

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

Example : Say, you start with the following code.

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 .

OperandDescription
<OnTrue>The return expression of the operator in case the condition evaluates to
<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

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:

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:

  • Python One Line Ternary

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 :

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.

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.

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 boost your coding and analytical skills . You’ll learn about advanced Python features such as list comprehension , slicing , lambda functions , regular expressions , map and reduce functions, and 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!!

Conditional expression (ternary operator) in Python

Python has a conditional expression (sometimes called a "ternary operator"). You can write operations like if statements in one line with conditional expressions.

  • 6. Expressions - Conditional expressions — Python 3.11.3 documentation

Basics of the conditional expression (ternary operator)

If ... elif ... else ... by conditional expressions, list comprehensions and conditional expressions, lambda expressions and conditional expressions.

See the following article for if statements in Python.

  • Python if statements (if, elif, else)

In Python, the conditional expression is written as follows.

The condition is evaluated first. If condition is True , X is evaluated and its value is returned, and if condition is False , Y is evaluated and its value is returned.

If you want to switch the value based on a condition, simply use the desired values in the conditional expression.

If you want to switch between operations based on a condition, simply describe each corresponding expression in the conditional expression.

An expression that does not return a value (i.e., an expression that returns None ) is also acceptable in a conditional expression. Depending on the condition, either expression will be evaluated and executed.

The above example is equivalent to the following code written with an if statement.

You can also combine multiple conditions using logical operators such as and or or .

  • Boolean operators in Python (and, or, not)

By combining conditional expressions, you can write an operation like if ... elif ... else ... in one line.

However, it is difficult to understand, so it may be better not to use it often.

The following two interpretations are possible, but the expression is processed as the first one.

In the sample code below, which includes three expressions, the first expression is interpreted like the second, rather than the third:

By using conditional expressions in list comprehensions, you can apply operations to the elements of the list based on the condition.

See the following article for details on list comprehensions.

  • List comprehensions in Python

Conditional expressions are also useful when you want to apply an operation similar to an if statement within lambda expressions.

In the example above, the lambda expression is assigned to a variable for convenience, but this is not recommended by PEP8.

Refer to the following article for more details on lambda expressions.

  • Lambda expressions in Python

Related Categories

Related articles.

  • Shallow and deep copy in Python: copy(), deepcopy()
  • Composite two images according to a mask image with Python, Pillow
  • OpenCV, NumPy: Rotate and flip image
  • pandas: Check if DataFrame/Series is empty
  • Check pandas version: pd.show_versions
  • Python if statement (if, elif, else)
  • pandas: Find the quantile with quantile()
  • Handle date and time with the datetime module in Python
  • Get image size (width, height) with Python, OpenCV, Pillow (PIL)
  • Convert between Unix time (Epoch time) and datetime in Python
  • Convert BGR and RGB with Python, OpenCV (cvtColor)
  • Matrix operations with NumPy in Python
  • pandas: Replace values in DataFrame and Series with replace()
  • Uppercase and lowercase strings in Python (conversion and checking)
  • Calculate mean, median, mode, variance, standard deviation in Python

Datagy logo

  • Learn Python
  • Python Lists
  • Python Dictionaries
  • Python Strings
  • Python Functions
  • Learn Pandas & NumPy
  • Pandas Tutorials
  • Numpy Tutorials
  • Learn Data Visualization
  • Python Seaborn
  • Python Matplotlib

Inline If in Python: The Ternary Operator in Python

  • September 16, 2021 December 20, 2022

Inline If Python Cover Image

In this tutorial, you’ll learn how to create inline if statements in Python. This is often known as the Python ternary operator, which allows you to execute conditional if statements in a single line, allowing statements to take up less space and often be written in my easy-to-understand syntax! Let’s take a look at what you’ll learn.

The Quick Answer: Use the Python Ternary Operator

Quick Answer - Inline If Python

Table of Contents

What is the Python Ternary Operator?

A ternary operator is an inline statement that evaluates a condition and returns one of two outputs. It’s an operator that’s often used in many programming languages, including Python, as well as math. The Python ternary operator has been around since Python 2.5, despite being delayed multiple times.

The syntax of the Python ternary operator is a little different than that of other languages. Let’s take a look at what it looks like:

Now let’s take a look at how you can actually write an inline if statement in Python.

How Do you Write an Inline If Statement in Python?

Before we dive into writing an inline if statement in Python, let’s take a look at how if statements actually work in Python. With an if statement you must include an if , but you can also choose to include an else statement, as well as one more of else-ifs, which in Python are written as elif .

The traditional Python if statement looks like this:

This can be a little cumbersome to write, especially if you conditions are very simple. Because of this, inline if statements in Python can be really helpful to help you write your code faster.

Let’s take a look at how we can accomplish this in Python:

This is significantly easier to write. Let’s break this down a little bit:

  • We assign a value to x , which will be evaluated
  • We declare a variable, y , which we assign to the value of 10, if x is True. Otherwise, we assign it a value of 20.

We can see how this is written out in a much more plain language than a for-loop that may require multiple lines, thereby wasting space.

Tip! This is quite similar to how you’d written a list comprehension. If you want to learn more about Python List Comprehensions, check out my in-depth tutorial here . If you want to learn more about Python for-loops, check out my in-depth guide here .

Now that you know how to write a basic inline if statement in Python, let’s see how you can simplify it even further by omitting the else statement.

How To Write an Inline If Statement Without an Else Statement

Now that you know how to write an inline if statement in Python with an else clause, let’s take a look at how we can do this in Python.

Before we do this, let’s see how we can do this with a traditional if statement in Python

You can see that this still requires you to write two lines. But we know better – we can easily cut this down to a single line. Let’s get started!

We can see here that really what this accomplishes is remove the line break between the if line and the code it executes.

Now let’s take a look at how we can even include an elif clause in our inline if statements in Python!

Check out some other Python tutorials on datagy.io, including our complete guide to styling Pandas and our comprehensive overview of Pivot Tables in Pandas !

How to Write an Inline If Statement With an Elif Statement

Including an else-if, or elif , in your Python inline if statement is a little less intuitive. But it’s definitely doable! So let’s get started. Let’s imagine we want to write this if-statement:

Let’s see how we can easily turn this into an inline if statement in Python:

This is a bit different than what we’ve seen so far, so let’s break it down a bit:

  • First, we evaluate is x == 1. If that’s true, the conditions end and y = 10.
  • Otherwise, we create another condition in brackets
  • First we check if x == 20, and if that’s true, then y = 20. Note that we did not repeated y= here.
  • Finally, if neither of the other decisions are true, we assign 30 to y

This is definitely a bit more complex to read, so you may be better off creating a traditional if statement.

In this post, you learned how to create inline if statement in Python! You learned about the Python ternary operator and how it works. You also learned how to create inline if statements with else statements, without else statements, as well as with else if statements.

To learn more about Python ternary operators, check out the official documentation here .

Nik Piepenbreier

Nik is the author of datagy.io and has over a decade of experience working with data analytics, data science, and Python. He specializes in teaching developers how to use Python for data science using hands-on tutorials. View Author posts

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Save my name, email, and website in this browser for the next time I comment.

  • Python Course
  • Python Basics
  • Interview Questions
  • Python Quiz
  • Popular Packages
  • Python Projects
  • Practice Python
  • AI With Python
  • Learn Python3
  • Python Automation
  • Python Web Dev
  • DSA with Python
  • Python OOPs
  • Dictionaries

Conditional Statements in Python

Understanding and mastering Python’s conditional statements is fundamental for any programmer aspiring to write efficient and robust code. In this guide, we’ll delve into the intricacies of conditional statements in Python, covering the basics, advanced techniques, and best practices.

  • What are Conditional Statements?

Conditional Statements are statements in Python that provide a choice for the control flow based on a condition. It means that the control flow of the Python program will be decided based on the outcome of the condition. Now let us see how Conditional Statements are implemented in Python.

  • Types of Conditional Statements in Python

1. If Conditional Statement in Python

2. if else conditional statements in python, 3. nested if..else conditional statements in python, 4. if-elif-else conditional statements in python, 5. ternary expression conditional statements in python, best practices for using conditional statements.

If the simple code of block is to be performed if the condition holds then the if statement is used. Here the condition mentioned holds then the code of the block runs otherwise not.

Syntax of If Statement :

In a conditional if Statement the additional block of code is merged as an else statement which is performed when if condition is false. 

Syntax of Python If-Else : 

Nested if..else means an if-else statement inside another if statement. Or in simple words first, there is an outer if statement, and inside it another if – else statement is present and such type of statement is known as nested if statement. We can use one if or else if statement inside another if or else if statements.

The if statements are executed from the top down. As soon as one of the conditions controlling the if is true, the statement associated with that if is executed, and the rest of the ladder is bypassed. If none of the conditions is true, then the final “else” statement will be executed.

The Python ternary Expression determines if a condition is true or false and then returns the appropriate value in accordance with the result. The ternary Expression is useful in cases where we need to assign a value to a variable based on a simple condition, and we want to keep our code more concise — all in just one line of code.

Syntax of Ternary Expression

  • Keep conditions simple and expressive for better readability.
  • Avoid deeply nested conditional blocks; refactor complex logic into smaller, more manageable functions.
  • Comment on complex conditions to clarify their purpose.
  • Prefer the ternary operator for simple conditional assignments.
  • Advanced Techniques:
  • Using short-circuit evaluation for efficiency in complex conditions.
  • Leveraging the any() and all() functions with conditions applied to iterables.
  • Employing conditional expressions within list comprehensions and generator expressions.

Conditional Statements in Python – FAQs

What are conditional statements in python.

Conditional statements in Python are used to execute a specific block of code based on the truth value of a condition. The most common conditional statements in Python are if , elif , and else . These allow the program to react differently depending on whether a condition (or a series of conditions) is true or false. x = 10 if x > 5: print("x is greater than 5") elif x == 5: print("x is equal to 5") else: print("x is less than 5")

What is a Conditional Expression in Python?

A conditional expression (also known as a ternary operator) in Python provides a method to simplify conditional statements. It allows for a quick definition of a condition and two possible outcomes (one if the condition is true, and one if the condition is false). The syntax is value_if_true if condition else value_if_false . # Conditional expression example x = 5 result = "High" if x > 10 else "Low" print(result) # Outputs: "Low"

What are Decision-Making Statements in Python?

Decision-making statements in Python help to control the flow of execution based on certain conditions. These include: if statement: Executes a block of code if a specified condition is true. if-else statement: Executes one block of code if the condition is true, and another block if the condition is false. elif (else if) statement: Checks multiple conditions in a sequence and executes a block of code as soon as one of the conditions evaluates to true. Nested if statements: You can nest if statements within another if or else block to create complex decision trees.

What are Conditional Selection Statements in Python?

Conditional selection statements refer to the use of if , elif , and else statements that select specific blocks of code to execute based on conditions. These statements are fundamental for branching in programming, allowing different outcomes depending on the input or state of the program.

What are the Conditional Loops in Python?

While Python supports loops that can incorporate conditions, the term “conditional loops” might specifically refer to loops that run based on a condition. Python provides two primary types of such loops: while loop: Continues to execute as long as a given condition is true. It checks the condition before executing the loop body. # while loop example x = 5 while x < 10: print(x) x += 1 for loop: Iterates over a sequence (like a list, tuple, or string) and executes the loop body for each item in the sequence. Although not traditionally a “conditional” loop, it can incorporate conditions using break and continue to control the loop execution dynamically. # for loop example with condition for i in range(10): if i == 5: break # Exit the loop when i is 5 print(i) These explanations outline how Python uses conditional statements and expressions to manage the flow of execution and make decisions within programs, crucial for creating dynamic and responsive applications

Please Login to comment...

Similar reads.

  • OpenAI o1 AI Model Launched: Explore o1-Preview, o1-Mini, Pricing & Comparison
  • How to Merge Cells in Google Sheets: Step by Step Guide
  • How to Lock Cells in Google Sheets : Step by Step Guide
  • PS5 Pro Launched: Controller, Price, Specs & Features, How to Pre-Order, and More
  • #geekstreak2024 – 21 Days POTD Challenge Powered By Deutsche Bank

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

How to Write the Python if Statement in one Line

Author's photo

  • online practice

Have you ever heard of writing a Python if statement in a single line? Here, we explore multiple ways to do exactly that, including using conditional expressions in Python.

The if statement is one of the most fundamental statements in Python. In this article, we learn how to write the Python if in one line.

The if is a key piece in writing Python code. It allows developers to control the flow and logic of their code based on information received at runtime. However, many Python developers do not know they may reduce the length and complexity of their if statements by writing them in a single line.

For this article, we assume you’re somewhat familiar with Python conditions and comparisons. If not, don’t worry! Our Python Basics Course will get you up to speed in no time. This course is included in the Python Basics Track , a full-fledged Python learning track designed for complete beginners.

We start with a recap on how Python if statements work. Then, we explore some examples of how to write if statements in a single line. Let’s get started!

How the if Statement Works in Python

Let’s start with the basics. An if statement in Python is used to determine whether a condition is True or False . This information can then be used to perform specific actions in the code, essentially controlling its logic during execution.

The structure of the basic if statement is as follows:

The <expression> is the code that evaluates to either True or False . If this code evaluates to True, then the code below (represented by <perform_action> ) executes.

Python uses whitespaces to indicate which lines are controlled by the if statement. The if statement controls all indented lines below it. Typically, the indentation is set to four spaces (read this post if you’re having trouble with the indentation ).

As a simple example, the code below prints a message if and only if the current weather is sunny:

The if statement in Python has two optional components: the elif statement, which executes only if the preceding if/elif statements are False ; and the else statement, which executes only if all of the preceding if/elif statements are False. While we may have as many elif statements as we want, we may only have a single else statement at the very end of the code block.

Here’s the basic structure:

Here’s how our previous example looks after adding elif and else statements. Change the value of the weather variable to see a different message printed:

How to Write a Python if in one Line

Writing an if statement in Python (along with the optional elif and else statements) uses a lot of whitespaces. Some people may find it confusing or tiresome to follow each statement and its corresponding indented lines.

To overcome this, there is a trick many Python developers often overlook: write an if statement in a single line !

Though not the standard, Python does allow us to write an if statement and its associated action in the same line. Here’s the basic structure:

As you can see, not much has changed. We simply need to “pull” the indented line <perform_action> up to the right of the colon character ( : ). It’s that simple!

Let’s check it with a real example. The code below works as it did previously despite the if statement being in a single line. Test it out and see for yourself:

Writing a Python if Statement With Multiple Actions in one Line

That’s all well and good, but what if my if statement has multiple actions under its control? When using the standard indentation, we separate different actions in multiple indented lines as the structure below shows:

Can we do this in a single line? The surprising answer is yes! We use semicolons to separate each action in the same line as if placed in different lines.

Here’s how the structure looks:

And an example of this functionality:

Have you noticed how each call to the print() function appears in its own line? This indicates we have successfully executed multiple actions from a single line. Nice!

By the way, interested in learning more about the print() function? We have an article on the ins and outs of the print() function .

Writing a Full Python if/elif/else Block Using Single Lines

You may have seen this coming, but we can even write elif and else statements each in a single line. To do so, we use the same syntax as writing an if statement in a single line.

Here’s the general structure:

Looks simple, right? Depending on the content of your expressions and actions, you may find this structure easier to read and understand compared to the indented blocks.

Here’s our previous example of a full if/elif/else block, rewritten as single lines:

Using Python Conditional Expressions to Write an if/else Block in one Line

There’s still a final trick to writing a Python if in one line. Conditional expressions in Python (also known as Python ternary operators) can run an if/else block in a single line.

A conditional expression is even more compact! Remember it took at least two lines to write a block containing both if and else statements in our last example.

In contrast, here’s how a conditional expression is structured:

The syntax is somewhat harder to follow at first, but the basic idea is that <expression> is a test. If the test evaluates to True , then <value_if_true> is the result. Otherwise, the expression results in <value_if_false> .

As you can see, conditional expressions always evaluate to a single value in the end. They are not complete replacements for an if/elif/else block. In fact, we cannot have elif statements in them at all. However, they’re most helpful when determining a single value depending on a single condition.

Take a look at the code below, which determines the value of is_baby depending on whether or not the age is below five:

This is the exact use case for a conditional expression! Here’s how we rewrite this if/else block in a single line:

Much simpler!

Go Even Further With Python!

We hope you now know many ways to write a Python if in one line. We’ve reached the end of the article, but don’t stop practicing now!

If you do not know where to go next, read this post on how to get beyond the basics in Python . If you’d rather get technical, we have a post on the best code editors and IDEs for Python . Remember to keep improving!

You may also like

python assignment conditional

How Do You Write a SELECT Statement in SQL?

python assignment conditional

What Is a Foreign Key in SQL?

python assignment conditional

Enumerate and Explain All the Basic Elements of an SQL Query

  • Contributors

Basic Statements in Python

Table of contents, what is a statement in python, statement set, multi-line statements, simple statements, expression statements, the assert statement, the try statement.

Statements in Python

In Python, statements are instructions or commands that you write to perform specific actions or tasks. They are the building blocks of a Python program.

A statement is a line of code that performs a specific action. It is the smallest unit of code that can be executed by the Python interpreter.

Assignment Statement

In this example, the value 10 is assigned to the variable x using the assignment statement.

Conditional Statement

In this example, the if-else statement is used to check the value of x and print a corresponding message.

By using statements, programmers can instruct the computer to perform a variety of tasks, from simple arithmetic operations to complex decision-making processes. Proper use of statements is crucial to writing efficient and effective Python code.

Here's a table summarizing various types of statements in Python:

Statement Description
Multi-Line Statements Statements spanning multiple lines using line continuation or braces.
Compound Statements Statements that contain other statements (e.g., , while, for).
Simple Statements Basic standalone statements that perform a single action.
Expression Statements Statements that evaluate and produce a value.
Statement A placeholder statement that does nothing.
Statement Used to delete references to objects.
Statement Terminates a function and returns a value (optional).
Statement Imports modules or specific objects from modules.
and Statements Control flow statements used in loops ( skips to the next iteration, exits the loop).

Please note that this table provides a brief overview of each statement type, and there may be additional details and variations for each statement.

Multi-line statements are a convenient way to write long code in Python without making it cluttered. They allow you to write several lines of code as a single statement, making it easier for developers to read and understand the code. Here are two examples of multi-line statements in Python:

  • Using backslash:
  • Using parentheses:

Simple statements are the smallest unit of execution in Python programming language and they do not contain any logical or conditional expressions. They are usually composed of a single line of code and can perform basic operations such as assigning values to variables , printing out values, or calling functions .

Examples of simple statements in Python:

Simple statements are essential to programming in Python and are often used in combination with more complex statements to create robust programs and applications.

Expression statements in Python are lines of code that evaluate and produce a value. They are used to assign values to variables, call functions, and perform other operations that produce a result.

In this example, we assign the value 5 to the variable x , then add 3 to x and assign the result ( 8 ) to the variable y . Finally, we print the value of y .

In this example, we define a function square that takes one argument ( x ) and returns its square. We then call the function with the argument 5 and assign the result ( 25 ) to the variable result . Finally, we print the value of result .

Overall, expression statements are an essential part of Python programming and allow for the execution of mathematical and computational operations.

The assert statement in Python is used to test conditions and trigger an error if the condition is not met. It is often used for debugging and testing purposes.

Where condition is the expression that is tested, and message is the optional error message that is displayed when the condition is not met.

In this example, the assert statement tests whether x is equal to 5 . If the condition is met, the statement has no effect. If the condition is not met, an error will be raised with the message x should be 5 .

In this example, the assert statement tests whether y is not equal to 0 before performing the division. If the condition is met, the division proceeds as normal. If the condition is not met, an error will be raised with the message Cannot divide by zero .

Overall, assert statements are a useful tool in Python for debugging and testing, as they can help catch errors early on. They are also easily disabled in production code to avoid any unnecessary overhead.

The try statement in Python is used to catch exceptions that may occur during the execution of a block of code. It ensures that even when an error occurs, the code does not stop running.

Examples of Error Processing

Dive deep into the topic.

  • Match Statements
  • Operators in Python Statements
  • The IF Statement

Contribute with us!

Do not hesitate to contribute to Python tutorials on GitHub: create a fork, update content and issue a pull request.

Profile picture for user AliaksandrSumich

  • Python »
  • 3.12.6 Documentation »
  • The Python Language Reference »
  • 6. Expressions
  • Theme Auto Light Dark |

6. Expressions ¶

This chapter explains the meaning of the elements of expressions in Python.

Syntax Notes: In this and the following chapters, extended BNF notation will be used to describe syntax, not lexical analysis. When (one alternative of) a syntax rule has the form

and no semantics are given, the semantics of this form of name are the same as for othername .

6.1. Arithmetic conversions ¶

When a description of an arithmetic operator below uses the phrase “the numeric arguments are converted to a common type”, this means that the operator implementation for built-in types works as follows:

If either argument is a complex number, the other is converted to complex;

otherwise, if either argument is a floating-point number, the other is converted to floating point;

otherwise, both must be integers and no conversion is necessary.

Some additional rules apply for certain operators (e.g., a string as a left argument to the ‘%’ operator). Extensions must define their own conversion behavior.

6.2. Atoms ¶

Atoms are the most basic elements of expressions. The simplest atoms are identifiers or literals. Forms enclosed in parentheses, brackets or braces are also categorized syntactically as atoms. The syntax for atoms is:

6.2.1. Identifiers (Names) ¶

An identifier occurring as an atom is a name. See section Identifiers and keywords for lexical definition and section Naming and binding for documentation of naming and binding.

When the name is bound to an object, evaluation of the atom yields that object. When a name is not bound, an attempt to evaluate it raises a NameError exception.

6.2.1.1. Private name mangling ¶

When an identifier that textually occurs in a class definition begins with two or more underscore characters and does not end in two or more underscores, it is considered a private name of that class.

The class specifications .

More precisely, private names are transformed to a longer form before code is generated for them. If the transformed name is longer than 255 characters, implementation-defined truncation may happen.

The transformation is independent of the syntactical context in which the identifier is used but only the following private identifiers are mangled:

Any name used as the name of a variable that is assigned or read or any name of an attribute being accessed.

The __name__ attribute of nested functions, classes, and type aliases is however not mangled.

The name of imported modules, e.g., __spam in import __spam . If the module is part of a package (i.e., its name contains a dot), the name is not mangled, e.g., the __foo in import __foo.bar is not mangled.

The name of an imported member, e.g., __f in from spam import __f .

The transformation rule is defined as follows:

The class name, with leading underscores removed and a single leading underscore inserted, is inserted in front of the identifier, e.g., the identifier __spam occurring in a class named Foo , _Foo or __Foo is transformed to _Foo__spam .

If the class name consists only of underscores, the transformation is the identity, e.g., the identifier __spam occurring in a class named _ or __ is left as is.

6.2.2. Literals ¶

Python supports string and bytes literals and various numeric literals:

Evaluation of a literal yields an object of the given type (string, bytes, integer, floating-point number, complex number) with the given value. The value may be approximated in the case of floating-point and imaginary (complex) literals. See section Literals for details.

All literals correspond to immutable data types, and hence the object’s identity is less important than its value. Multiple evaluations of literals with the same value (either the same occurrence in the program text or a different occurrence) may obtain the same object or a different object with the same value.

6.2.3. Parenthesized forms ¶

A parenthesized form is an optional expression list enclosed in parentheses:

A parenthesized expression list yields whatever that expression list yields: if the list contains at least one comma, it yields a tuple; otherwise, it yields the single expression that makes up the expression list.

An empty pair of parentheses yields an empty tuple object. Since tuples are immutable, the same rules as for literals apply (i.e., two occurrences of the empty tuple may or may not yield the same object).

Note that tuples are not formed by the parentheses, but rather by use of the comma. The exception is the empty tuple, for which parentheses are required — allowing unparenthesized “nothing” in expressions would cause ambiguities and allow common typos to pass uncaught.

6.2.4. Displays for lists, sets and dictionaries ¶

For constructing a list, a set or a dictionary Python provides special syntax called “displays”, each of them in two flavors:

either the container contents are listed explicitly, or

they are computed via a set of looping and filtering instructions, called a comprehension .

Common syntax elements for comprehensions are:

The comprehension consists of a single expression followed by at least one for clause and zero or more for or if clauses. In this case, the elements of the new container are those that would be produced by considering each of the for or if clauses a block, nesting from left to right, and evaluating the expression to produce an element each time the innermost block is reached.

However, aside from the iterable expression in the leftmost for clause, the comprehension is executed in a separate implicitly nested scope. This ensures that names assigned to in the target list don’t “leak” into the enclosing scope.

The iterable expression in the leftmost for clause is evaluated directly in the enclosing scope and then passed as an argument to the implicitly nested scope. Subsequent for clauses and any filter condition in the leftmost for clause cannot be evaluated in the enclosing scope as they may depend on the values obtained from the leftmost iterable. For example: [x*y for x in range(10) for y in range(x, x+10)] .

To ensure the comprehension always results in a container of the appropriate type, yield and yield from expressions are prohibited in the implicitly nested scope.

Since Python 3.6, in an async def function, an async for clause may be used to iterate over a asynchronous iterator . A comprehension in an async def function may consist of either a for or async for clause following the leading expression, may contain additional for or async for clauses, and may also use await expressions.

If a comprehension contains async for clauses, or if it contains await expressions or other asynchronous comprehensions anywhere except the iterable expression in the leftmost for clause, it is called an asynchronous comprehension . An asynchronous comprehension may suspend the execution of the coroutine function in which it appears. See also PEP 530 .

Added in version 3.6: Asynchronous comprehensions were introduced.

Changed in version 3.8: yield and yield from prohibited in the implicitly nested scope.

Changed in version 3.11: Asynchronous comprehensions are now allowed inside comprehensions in asynchronous functions. Outer comprehensions implicitly become asynchronous.

6.2.5. List displays ¶

A list display is a possibly empty series of expressions enclosed in square brackets:

A list display yields a new list object, the contents being specified by either a list of expressions or a comprehension. When a comma-separated list of expressions is supplied, its elements are evaluated from left to right and placed into the list object in that order. When a comprehension is supplied, the list is constructed from the elements resulting from the comprehension.

6.2.6. Set displays ¶

A set display is denoted by curly braces and distinguishable from dictionary displays by the lack of colons separating keys and values:

A set display yields a new mutable set object, the contents being specified by either a sequence of expressions or a comprehension. When a comma-separated list of expressions is supplied, its elements are evaluated from left to right and added to the set object. When a comprehension is supplied, the set is constructed from the elements resulting from the comprehension.

An empty set cannot be constructed with {} ; this literal constructs an empty dictionary.

6.2.7. Dictionary displays ¶

A dictionary display is a possibly empty series of dict items (key/value pairs) enclosed in curly braces:

A dictionary display yields a new dictionary object.

If a comma-separated sequence of dict items is given, they are evaluated from left to right to define the entries of the dictionary: each key object is used as a key into the dictionary to store the corresponding value. This means that you can specify the same key multiple times in the dict item list, and the final dictionary’s value for that key will be the last one given.

A double asterisk ** denotes dictionary unpacking . Its operand must be a mapping . Each mapping item is added to the new dictionary. Later values replace values already set by earlier dict items and earlier dictionary unpackings.

Added in version 3.5: Unpacking into dictionary displays, originally proposed by PEP 448 .

A dict comprehension, in contrast to list and set comprehensions, needs two expressions separated with a colon followed by the usual “for” and “if” clauses. When the comprehension is run, the resulting key and value elements are inserted in the new dictionary in the order they are produced.

Restrictions on the types of the key values are listed earlier in section The standard type hierarchy . (To summarize, the key type should be hashable , which excludes all mutable objects.) Clashes between duplicate keys are not detected; the last value (textually rightmost in the display) stored for a given key value prevails.

Changed in version 3.8: Prior to Python 3.8, in dict comprehensions, the evaluation order of key and value was not well-defined. In CPython, the value was evaluated before the key. Starting with 3.8, the key is evaluated before the value, as proposed by PEP 572 .

6.2.8. Generator expressions ¶

A generator expression is a compact generator notation in parentheses:

A generator expression yields a new generator object. Its syntax is the same as for comprehensions, except that it is enclosed in parentheses instead of brackets or curly braces.

Variables used in the generator expression are evaluated lazily when the __next__() method is called for the generator object (in the same fashion as normal generators). However, the iterable expression in the leftmost for clause is immediately evaluated, so that an error produced by it will be emitted at the point where the generator expression is defined, rather than at the point where the first value is retrieved. Subsequent for clauses and any filter condition in the leftmost for clause cannot be evaluated in the enclosing scope as they may depend on the values obtained from the leftmost iterable. For example: (x*y for x in range(10) for y in range(x, x+10)) .

The parentheses can be omitted on calls with only one argument. See section Calls for details.

To avoid interfering with the expected operation of the generator expression itself, yield and yield from expressions are prohibited in the implicitly defined generator.

If a generator expression contains either async for clauses or await expressions it is called an asynchronous generator expression . An asynchronous generator expression returns a new asynchronous generator object, which is an asynchronous iterator (see Asynchronous Iterators ).

Added in version 3.6: Asynchronous generator expressions were introduced.

Changed in version 3.7: Prior to Python 3.7, asynchronous generator expressions could only appear in async def coroutines. Starting with 3.7, any function can use asynchronous generator expressions.

6.2.9. Yield expressions ¶

The yield expression is used when defining a generator function or an asynchronous generator function and thus can only be used in the body of a function definition. Using a yield expression in a function’s body causes that function to be a generator function, and using it in an async def function’s body causes that coroutine function to be an asynchronous generator function. For example:

Due to their side effects on the containing scope, yield expressions are not permitted as part of the implicitly defined scopes used to implement comprehensions and generator expressions.

Changed in version 3.8: Yield expressions prohibited in the implicitly nested scopes used to implement comprehensions and generator expressions.

Generator functions are described below, while asynchronous generator functions are described separately in section Asynchronous generator functions .

When a generator function is called, it returns an iterator known as a generator. That generator then controls the execution of the generator function. The execution starts when one of the generator’s methods is called. At that time, the execution proceeds to the first yield expression, where it is suspended again, returning the value of expression_list to the generator’s caller, or None if expression_list is omitted. By suspended, we mean that all local state is retained, including the current bindings of local variables, the instruction pointer, the internal evaluation stack, and the state of any exception handling. When the execution is resumed by calling one of the generator’s methods, the function can proceed exactly as if the yield expression were just another external call. The value of the yield expression after resuming depends on the method which resumed the execution. If __next__() is used (typically via either a for or the next() builtin) then the result is None . Otherwise, if send() is used, then the result will be the value passed in to that method.

All of this makes generator functions quite similar to coroutines; they yield multiple times, they have more than one entry point and their execution can be suspended. The only difference is that a generator function cannot control where the execution should continue after it yields; the control is always transferred to the generator’s caller.

Yield expressions are allowed anywhere in a try construct. If the generator is not resumed before it is finalized (by reaching a zero reference count or by being garbage collected), the generator-iterator’s close() method will be called, allowing any pending finally clauses to execute.

When yield from <expr> is used, the supplied expression must be an iterable. The values produced by iterating that iterable are passed directly to the caller of the current generator’s methods. Any values passed in with send() and any exceptions passed in with throw() are passed to the underlying iterator if it has the appropriate methods. If this is not the case, then send() will raise AttributeError or TypeError , while throw() will just raise the passed in exception immediately.

When the underlying iterator is complete, the value attribute of the raised StopIteration instance becomes the value of the yield expression. It can be either set explicitly when raising StopIteration , or automatically when the subiterator is a generator (by returning a value from the subgenerator).

Changed in version 3.3: Added yield from <expr> to delegate control flow to a subiterator.

The parentheses may be omitted when the yield expression is the sole expression on the right hand side of an assignment statement.

The proposal for adding generators and the yield statement to Python.

The proposal to enhance the API and syntax of generators, making them usable as simple coroutines.

The proposal to introduce the yield_from syntax, making delegation to subgenerators easy.

The proposal that expanded on PEP 492 by adding generator capabilities to coroutine functions.

6.2.9.1. Generator-iterator methods ¶

This subsection describes the methods of a generator iterator. They can be used to control the execution of a generator function.

Note that calling any of the generator methods below when the generator is already executing raises a ValueError exception.

Starts the execution of a generator function or resumes it at the last executed yield expression. When a generator function is resumed with a __next__() method, the current yield expression always evaluates to None . The execution then continues to the next yield expression, where the generator is suspended again, and the value of the expression_list is returned to __next__() ’s caller. If the generator exits without yielding another value, a StopIteration exception is raised.

This method is normally called implicitly, e.g. by a for loop, or by the built-in next() function.

Resumes the execution and “sends” a value into the generator function. The value argument becomes the result of the current yield expression. The send() method returns the next value yielded by the generator, or raises StopIteration if the generator exits without yielding another value. When send() is called to start the generator, it must be called with None as the argument, because there is no yield expression that could receive the value.

Raises an exception at the point where the generator was paused, and returns the next value yielded by the generator function. If the generator exits without yielding another value, a StopIteration exception is raised. If the generator function does not catch the passed-in exception, or raises a different exception, then that exception propagates to the caller.

In typical use, this is called with a single exception instance similar to the way the raise keyword is used.

For backwards compatibility, however, the second signature is supported, following a convention from older versions of Python. The type argument should be an exception class, and value should be an exception instance. If the value is not provided, the type constructor is called to get an instance. If traceback is provided, it is set on the exception, otherwise any existing __traceback__ attribute stored in value may be cleared.

Changed in version 3.12: The second signature (type[, value[, traceback]]) is deprecated and may be removed in a future version of Python.

Raises a GeneratorExit at the point where the generator function was paused. If the generator function then exits gracefully, is already closed, or raises GeneratorExit (by not catching the exception), close returns to its caller. If the generator yields a value, a RuntimeError is raised. If the generator raises any other exception, it is propagated to the caller. close() does nothing if the generator has already exited due to an exception or normal exit.

6.2.9.2. Examples ¶

Here is a simple example that demonstrates the behavior of generators and generator functions:

For examples using yield from , see PEP 380: Syntax for Delegating to a Subgenerator in “What’s New in Python.”

6.2.9.3. Asynchronous generator functions ¶

The presence of a yield expression in a function or method defined using async def further defines the function as an asynchronous generator function.

When an asynchronous generator function is called, it returns an asynchronous iterator known as an asynchronous generator object. That object then controls the execution of the generator function. An asynchronous generator object is typically used in an async for statement in a coroutine function analogously to how a generator object would be used in a for statement.

Calling one of the asynchronous generator’s methods returns an awaitable object, and the execution starts when this object is awaited on. At that time, the execution proceeds to the first yield expression, where it is suspended again, returning the value of expression_list to the awaiting coroutine. As with a generator, suspension means that all local state is retained, including the current bindings of local variables, the instruction pointer, the internal evaluation stack, and the state of any exception handling. When the execution is resumed by awaiting on the next object returned by the asynchronous generator’s methods, the function can proceed exactly as if the yield expression were just another external call. The value of the yield expression after resuming depends on the method which resumed the execution. If __anext__() is used then the result is None . Otherwise, if asend() is used, then the result will be the value passed in to that method.

If an asynchronous generator happens to exit early by break , the caller task being cancelled, or other exceptions, the generator’s async cleanup code will run and possibly raise exceptions or access context variables in an unexpected context–perhaps after the lifetime of tasks it depends, or during the event loop shutdown when the async-generator garbage collection hook is called. To prevent this, the caller must explicitly close the async generator by calling aclose() method to finalize the generator and ultimately detach it from the event loop.

In an asynchronous generator function, yield expressions are allowed anywhere in a try construct. However, if an asynchronous generator is not resumed before it is finalized (by reaching a zero reference count or by being garbage collected), then a yield expression within a try construct could result in a failure to execute pending finally clauses. In this case, it is the responsibility of the event loop or scheduler running the asynchronous generator to call the asynchronous generator-iterator’s aclose() method and run the resulting coroutine object, thus allowing any pending finally clauses to execute.

To take care of finalization upon event loop termination, an event loop should define a finalizer function which takes an asynchronous generator-iterator and presumably calls aclose() and executes the coroutine. This finalizer may be registered by calling sys.set_asyncgen_hooks() . When first iterated over, an asynchronous generator-iterator will store the registered finalizer to be called upon finalization. For a reference example of a finalizer method see the implementation of asyncio.Loop.shutdown_asyncgens in Lib/asyncio/base_events.py .

The expression yield from <expr> is a syntax error when used in an asynchronous generator function.

6.2.9.4. Asynchronous generator-iterator methods ¶

This subsection describes the methods of an asynchronous generator iterator, which are used to control the execution of a generator function.

Returns an awaitable which when run starts to execute the asynchronous generator or resumes it at the last executed yield expression. When an asynchronous generator function is resumed with an __anext__() method, the current yield expression always evaluates to None in the returned awaitable, which when run will continue to the next yield expression. The value of the expression_list of the yield expression is the value of the StopIteration exception raised by the completing coroutine. If the asynchronous generator exits without yielding another value, the awaitable instead raises a StopAsyncIteration exception, signalling that the asynchronous iteration has completed.

This method is normally called implicitly by a async for loop.

Returns an awaitable which when run resumes the execution of the asynchronous generator. As with the send() method for a generator, this “sends” a value into the asynchronous generator function, and the value argument becomes the result of the current yield expression. The awaitable returned by the asend() method will return the next value yielded by the generator as the value of the raised StopIteration , or raises StopAsyncIteration if the asynchronous generator exits without yielding another value. When asend() is called to start the asynchronous generator, it must be called with None as the argument, because there is no yield expression that could receive the value.

Returns an awaitable that raises an exception of type type at the point where the asynchronous generator was paused, and returns the next value yielded by the generator function as the value of the raised StopIteration exception. If the asynchronous generator exits without yielding another value, a StopAsyncIteration exception is raised by the awaitable. If the generator function does not catch the passed-in exception, or raises a different exception, then when the awaitable is run that exception propagates to the caller of the awaitable.

Returns an awaitable that when run will throw a GeneratorExit into the asynchronous generator function at the point where it was paused. If the asynchronous generator function then exits gracefully, is already closed, or raises GeneratorExit (by not catching the exception), then the returned awaitable will raise a StopIteration exception. Any further awaitables returned by subsequent calls to the asynchronous generator will raise a StopAsyncIteration exception. If the asynchronous generator yields a value, a RuntimeError is raised by the awaitable. If the asynchronous generator raises any other exception, it is propagated to the caller of the awaitable. If the asynchronous generator has already exited due to an exception or normal exit, then further calls to aclose() will return an awaitable that does nothing.

6.3. Primaries ¶

Primaries represent the most tightly bound operations of the language. Their syntax is:

6.3.1. Attribute references ¶

An attribute reference is a primary followed by a period and a name:

The primary must evaluate to an object of a type that supports attribute references, which most objects do. This object is then asked to produce the attribute whose name is the identifier. The type and value produced is determined by the object. Multiple evaluations of the same attribute reference may yield different objects.

This production can be customized by overriding the __getattribute__() method or the __getattr__() method. The __getattribute__() method is called first and either returns a value or raises AttributeError if the attribute is not available.

If an AttributeError is raised and the object has a __getattr__() method, that method is called as a fallback.

6.3.2. Subscriptions ¶

The subscription of an instance of a container class will generally select an element from the container. The subscription of a generic class will generally return a GenericAlias object.

When an object is subscripted, the interpreter will evaluate the primary and the expression list.

The primary must evaluate to an object that supports subscription. An object may support subscription through defining one or both of __getitem__() and __class_getitem__() . When the primary is subscripted, the evaluated result of the expression list will be passed to one of these methods. For more details on when __class_getitem__ is called instead of __getitem__ , see __class_getitem__ versus __getitem__ .

If the expression list contains at least one comma, it will evaluate to a tuple containing the items of the expression list. Otherwise, the expression list will evaluate to the value of the list’s sole member.

For built-in objects, there are two types of objects that support subscription via __getitem__() :

Mappings. If the primary is a mapping , the expression list must evaluate to an object whose value is one of the keys of the mapping, and the subscription selects the value in the mapping that corresponds to that key. An example of a builtin mapping class is the dict class.

Sequences. If the primary is a sequence , the expression list must evaluate to an int or a slice (as discussed in the following section). Examples of builtin sequence classes include the str , list and tuple classes.

The formal syntax makes no special provision for negative indices in sequences . However, built-in sequences all provide a __getitem__() method that interprets negative indices by adding the length of the sequence to the index so that, for example, x[-1] selects the last item of x . The resulting value must be a nonnegative integer less than the number of items in the sequence, and the subscription selects the item whose index is that value (counting from zero). Since the support for negative indices and slicing occurs in the object’s __getitem__() method, subclasses overriding this method will need to explicitly add that support.

A string is a special kind of sequence whose items are characters . A character is not a separate data type but a string of exactly one character.

6.3.3. Slicings ¶

A slicing selects a range of items in a sequence object (e.g., a string, tuple or list). Slicings may be used as expressions or as targets in assignment or del statements. The syntax for a slicing:

There is ambiguity in the formal syntax here: anything that looks like an expression list also looks like a slice list, so any subscription can be interpreted as a slicing. Rather than further complicating the syntax, this is disambiguated by defining that in this case the interpretation as a subscription takes priority over the interpretation as a slicing (this is the case if the slice list contains no proper slice).

The semantics for a slicing are as follows. The primary is indexed (using the same __getitem__() method as normal subscription) with a key that is constructed from the slice list, as follows. If the slice list contains at least one comma, the key is a tuple containing the conversion of the slice items; otherwise, the conversion of the lone slice item is the key. The conversion of a slice item that is an expression is that expression. The conversion of a proper slice is a slice object (see section The standard type hierarchy ) whose start , stop and step attributes are the values of the expressions given as lower bound, upper bound and stride, respectively, substituting None for missing expressions.

6.3.4. Calls ¶

A call calls a callable object (e.g., a function ) with a possibly empty series of arguments :

An optional trailing comma may be present after the positional and keyword arguments but does not affect the semantics.

The primary must evaluate to a callable object (user-defined functions, built-in functions, methods of built-in objects, class objects, methods of class instances, and all objects having a __call__() method are callable). All argument expressions are evaluated before the call is attempted. Please refer to section Function definitions for the syntax of formal parameter lists.

If keyword arguments are present, they are first converted to positional arguments, as follows. First, a list of unfilled slots is created for the formal parameters. If there are N positional arguments, they are placed in the first N slots. Next, for each keyword argument, the identifier is used to determine the corresponding slot (if the identifier is the same as the first formal parameter name, the first slot is used, and so on). If the slot is already filled, a TypeError exception is raised. Otherwise, the argument is placed in the slot, filling it (even if the expression is None , it fills the slot). When all arguments have been processed, the slots that are still unfilled are filled with the corresponding default value from the function definition. (Default values are calculated, once, when the function is defined; thus, a mutable object such as a list or dictionary used as default value will be shared by all calls that don’t specify an argument value for the corresponding slot; this should usually be avoided.) If there are any unfilled slots for which no default value is specified, a TypeError exception is raised. Otherwise, the list of filled slots is used as the argument list for the call.

CPython implementation detail: An implementation may provide built-in functions whose positional parameters do not have names, even if they are ‘named’ for the purpose of documentation, and which therefore cannot be supplied by keyword. In CPython, this is the case for functions implemented in C that use PyArg_ParseTuple() to parse their arguments.

If there are more positional arguments than there are formal parameter slots, a TypeError exception is raised, unless a formal parameter using the syntax *identifier is present; in this case, that formal parameter receives a tuple containing the excess positional arguments (or an empty tuple if there were no excess positional arguments).

If any keyword argument does not correspond to a formal parameter name, a TypeError exception is raised, unless a formal parameter using the syntax **identifier is present; in this case, that formal parameter receives a dictionary containing the excess keyword arguments (using the keywords as keys and the argument values as corresponding values), or a (new) empty dictionary if there were no excess keyword arguments.

If the syntax *expression appears in the function call, expression must evaluate to an iterable . Elements from these iterables are treated as if they were additional positional arguments. For the call f(x1, x2, *y, x3, x4) , if y evaluates to a sequence y1 , …, yM , this is equivalent to a call with M+4 positional arguments x1 , x2 , y1 , …, yM , x3 , x4 .

A consequence of this is that although the *expression syntax may appear after explicit keyword arguments, it is processed before the keyword arguments (and any **expression arguments – see below). So:

It is unusual for both keyword arguments and the *expression syntax to be used in the same call, so in practice this confusion does not often arise.

If the syntax **expression appears in the function call, expression must evaluate to a mapping , the contents of which are treated as additional keyword arguments. If a parameter matching a key has already been given a value (by an explicit keyword argument, or from another unpacking), a TypeError exception is raised.

When **expression is used, each key in this mapping must be a string. Each value from the mapping is assigned to the first formal parameter eligible for keyword assignment whose name is equal to the key. A key need not be a Python identifier (e.g. "max-temp °F" is acceptable, although it will not match any formal parameter that could be declared). If there is no match to a formal parameter the key-value pair is collected by the ** parameter, if there is one, or if there is not, a TypeError exception is raised.

Formal parameters using the syntax *identifier or **identifier cannot be used as positional argument slots or as keyword argument names.

Changed in version 3.5: Function calls accept any number of * and ** unpackings, positional arguments may follow iterable unpackings ( * ), and keyword arguments may follow dictionary unpackings ( ** ). Originally proposed by PEP 448 .

A call always returns some value, possibly None , unless it raises an exception. How this value is computed depends on the type of the callable object.

The code block for the function is executed, passing it the argument list. The first thing the code block will do is bind the formal parameters to the arguments; this is described in section Function definitions . When the code block executes a return statement, this specifies the return value of the function call.

The result is up to the interpreter; see Built-in Functions for the descriptions of built-in functions and methods.

A new instance of that class is returned.

The corresponding user-defined function is called, with an argument list that is one longer than the argument list of the call: the instance becomes the first argument.

The class must define a __call__() method; the effect is then the same as if that method was called.

6.4. Await expression ¶

Suspend the execution of coroutine on an awaitable object. Can only be used inside a coroutine function .

Added in version 3.5.

6.5. The power operator ¶

The power operator binds more tightly than unary operators on its left; it binds less tightly than unary operators on its right. The syntax is:

Thus, in an unparenthesized sequence of power and unary operators, the operators are evaluated from right to left (this does not constrain the evaluation order for the operands): -1**2 results in -1 .

The power operator has the same semantics as the built-in pow() function, when called with two arguments: it yields its left argument raised to the power of its right argument. The numeric arguments are first converted to a common type, and the result is of that type.

For int operands, the result has the same type as the operands unless the second argument is negative; in that case, all arguments are converted to float and a float result is delivered. For example, 10**2 returns 100 , but 10**-2 returns 0.01 .

Raising 0.0 to a negative power results in a ZeroDivisionError . Raising a negative number to a fractional power results in a complex number. (In earlier versions it raised a ValueError .)

This operation can be customized using the special __pow__() and __rpow__() methods.

6.6. Unary arithmetic and bitwise operations ¶

All unary arithmetic and bitwise operations have the same priority:

The unary - (minus) operator yields the negation of its numeric argument; the operation can be overridden with the __neg__() special method.

The unary + (plus) operator yields its numeric argument unchanged; the operation can be overridden with the __pos__() special method.

The unary ~ (invert) operator yields the bitwise inversion of its integer argument. The bitwise inversion of x is defined as -(x+1) . It only applies to integral numbers or to custom objects that override the __invert__() special method.

In all three cases, if the argument does not have the proper type, a TypeError exception is raised.

6.7. Binary arithmetic operations ¶

The binary arithmetic operations have the conventional priority levels. Note that some of these operations also apply to certain non-numeric types. Apart from the power operator, there are only two levels, one for multiplicative operators and one for additive operators:

The * (multiplication) operator yields the product of its arguments. The arguments must either both be numbers, or one argument must be an integer and the other must be a sequence. In the former case, the numbers are converted to a common type and then multiplied together. In the latter case, sequence repetition is performed; a negative repetition factor yields an empty sequence.

This operation can be customized using the special __mul__() and __rmul__() methods.

The @ (at) operator is intended to be used for matrix multiplication. No builtin Python types implement this operator.

This operation can be customized using the special __matmul__() and __rmatmul__() methods.

The / (division) and // (floor division) operators yield the quotient of their arguments. The numeric arguments are first converted to a common type. Division of integers yields a float, while floor division of integers results in an integer; the result is that of mathematical division with the ‘floor’ function applied to the result. Division by zero raises the ZeroDivisionError exception.

The division operation can be customized using the special __truediv__() and __rtruediv__() methods. The floor division operation can be customized using the special __floordiv__() and __rfloordiv__() methods.

The % (modulo) operator yields the remainder from the division of the first argument by the second. The numeric arguments are first converted to a common type. A zero right argument raises the ZeroDivisionError exception. The arguments may be floating-point numbers, e.g., 3.14%0.7 equals 0.34 (since 3.14 equals 4*0.7 + 0.34 .) The modulo operator always yields a result with the same sign as its second operand (or zero); the absolute value of the result is strictly smaller than the absolute value of the second operand [ 1 ] .

The floor division and modulo operators are connected by the following identity: x == (x//y)*y + (x%y) . Floor division and modulo are also connected with the built-in function divmod() : divmod(x, y) == (x//y, x%y) . [ 2 ] .

In addition to performing the modulo operation on numbers, the % operator is also overloaded by string objects to perform old-style string formatting (also known as interpolation). The syntax for string formatting is described in the Python Library Reference, section printf-style String Formatting .

The modulo operation can be customized using the special __mod__() and __rmod__() methods.

The floor division operator, the modulo operator, and the divmod() function are not defined for complex numbers. Instead, convert to a floating-point number using the abs() function if appropriate.

The + (addition) operator yields the sum of its arguments. The arguments must either both be numbers or both be sequences of the same type. In the former case, the numbers are converted to a common type and then added together. In the latter case, the sequences are concatenated.

This operation can be customized using the special __add__() and __radd__() methods.

The - (subtraction) operator yields the difference of its arguments. The numeric arguments are first converted to a common type.

This operation can be customized using the special __sub__() and __rsub__() methods.

6.8. Shifting operations ¶

The shifting operations have lower priority than the arithmetic operations:

These operators accept integers as arguments. They shift the first argument to the left or right by the number of bits given by the second argument.

The left shift operation can be customized using the special __lshift__() and __rlshift__() methods. The right shift operation can be customized using the special __rshift__() and __rrshift__() methods.

A right shift by n bits is defined as floor division by pow(2,n) . A left shift by n bits is defined as multiplication with pow(2,n) .

6.9. Binary bitwise operations ¶

Each of the three bitwise operations has a different priority level:

The & operator yields the bitwise AND of its arguments, which must be integers or one of them must be a custom object overriding __and__() or __rand__() special methods.

The ^ operator yields the bitwise XOR (exclusive OR) of its arguments, which must be integers or one of them must be a custom object overriding __xor__() or __rxor__() special methods.

The | operator yields the bitwise (inclusive) OR of its arguments, which must be integers or one of them must be a custom object overriding __or__() or __ror__() special methods.

6.10. Comparisons ¶

Unlike C, all comparison operations in Python have the same priority, which is lower than that of any arithmetic, shifting or bitwise operation. Also unlike C, expressions like a < b < c have the interpretation that is conventional in mathematics:

Comparisons yield boolean values: True or False . Custom rich comparison methods may return non-boolean values. In this case Python will call bool() on such value in boolean contexts.

Comparisons can be chained arbitrarily, e.g., x < y <= z is equivalent to x < y and y <= z , except that y is evaluated only once (but in both cases z is not evaluated at all when x < y is found to be false).

Formally, if a , b , c , …, y , z are expressions and op1 , op2 , …, opN are comparison operators, then a op1 b op2 c ... y opN z is equivalent to a op1 b and b op2 c and ... y opN z , except that each expression is evaluated at most once.

Note that a op1 b op2 c doesn’t imply any kind of comparison between a and c , so that, e.g., x < y > z is perfectly legal (though perhaps not pretty).

6.10.1. Value comparisons ¶

The operators < , > , == , >= , <= , and != compare the values of two objects. The objects do not need to have the same type.

Chapter Objects, values and types states that objects have a value (in addition to type and identity). The value of an object is a rather abstract notion in Python: For example, there is no canonical access method for an object’s value. Also, there is no requirement that the value of an object should be constructed in a particular way, e.g. comprised of all its data attributes. Comparison operators implement a particular notion of what the value of an object is. One can think of them as defining the value of an object indirectly, by means of their comparison implementation.

Because all types are (direct or indirect) subtypes of object , they inherit the default comparison behavior from object . Types can customize their comparison behavior by implementing rich comparison methods like __lt__() , described in Basic customization .

The default behavior for equality comparison ( == and != ) is based on the identity of the objects. Hence, equality comparison of instances with the same identity results in equality, and equality comparison of instances with different identities results in inequality. A motivation for this default behavior is the desire that all objects should be reflexive (i.e. x is y implies x == y ).

A default order comparison ( < , > , <= , and >= ) is not provided; an attempt raises TypeError . A motivation for this default behavior is the lack of a similar invariant as for equality.

The behavior of the default equality comparison, that instances with different identities are always unequal, may be in contrast to what types will need that have a sensible definition of object value and value-based equality. Such types will need to customize their comparison behavior, and in fact, a number of built-in types have done that.

The following list describes the comparison behavior of the most important built-in types.

Numbers of built-in numeric types ( Numeric Types — int, float, complex ) and of the standard library types fractions.Fraction and decimal.Decimal can be compared within and across their types, with the restriction that complex numbers do not support order comparison. Within the limits of the types involved, they compare mathematically (algorithmically) correct without loss of precision.

The not-a-number values float('NaN') and decimal.Decimal('NaN') are special. Any ordered comparison of a number to a not-a-number value is false. A counter-intuitive implication is that not-a-number values are not equal to themselves. For example, if x = float('NaN') , 3 < x , x < 3 and x == x are all false, while x != x is true. This behavior is compliant with IEEE 754.

None and NotImplemented are singletons. PEP 8 advises that comparisons for singletons should always be done with is or is not , never the equality operators.

Binary sequences (instances of bytes or bytearray ) can be compared within and across their types. They compare lexicographically using the numeric values of their elements.

Strings (instances of str ) compare lexicographically using the numerical Unicode code points (the result of the built-in function ord() ) of their characters. [ 3 ]

Strings and binary sequences cannot be directly compared.

Sequences (instances of tuple , list , or range ) can be compared only within each of their types, with the restriction that ranges do not support order comparison. Equality comparison across these types results in inequality, and ordering comparison across these types raises TypeError .

Sequences compare lexicographically using comparison of corresponding elements. The built-in containers typically assume identical objects are equal to themselves. That lets them bypass equality tests for identical objects to improve performance and to maintain their internal invariants.

Lexicographical comparison between built-in collections works as follows:

For two collections to compare equal, they must be of the same type, have the same length, and each pair of corresponding elements must compare equal (for example, [1,2] == (1,2) is false because the type is not the same).

Collections that support order comparison are ordered the same as their first unequal elements (for example, [1,2,x] <= [1,2,y] has the same value as x <= y ). If a corresponding element does not exist, the shorter collection is ordered first (for example, [1,2] < [1,2,3] is true).

Mappings (instances of dict ) compare equal if and only if they have equal (key, value) pairs. Equality comparison of the keys and values enforces reflexivity.

Order comparisons ( < , > , <= , and >= ) raise TypeError .

Sets (instances of set or frozenset ) can be compared within and across their types.

They define order comparison operators to mean subset and superset tests. Those relations do not define total orderings (for example, the two sets {1,2} and {2,3} are not equal, nor subsets of one another, nor supersets of one another). Accordingly, sets are not appropriate arguments for functions which depend on total ordering (for example, min() , max() , and sorted() produce undefined results given a list of sets as inputs).

Comparison of sets enforces reflexivity of its elements.

Most other built-in types have no comparison methods implemented, so they inherit the default comparison behavior.

User-defined classes that customize their comparison behavior should follow some consistency rules, if possible:

Equality comparison should be reflexive. In other words, identical objects should compare equal:

x is y implies x == y

Comparison should be symmetric. In other words, the following expressions should have the same result:

x == y and y == x x != y and y != x x < y and y > x x <= y and y >= x

Comparison should be transitive. The following (non-exhaustive) examples illustrate that:

x > y and y > z implies x > z x < y and y <= z implies x < z

Inverse comparison should result in the boolean negation. In other words, the following expressions should have the same result:

x == y and not x != y x < y and not x >= y (for total ordering) x > y and not x <= y (for total ordering)

The last two expressions apply to totally ordered collections (e.g. to sequences, but not to sets or mappings). See also the total_ordering() decorator.

The hash() result should be consistent with equality. Objects that are equal should either have the same hash value, or be marked as unhashable.

Python does not enforce these consistency rules. In fact, the not-a-number values are an example for not following these rules.

6.10.2. Membership test operations ¶

The operators in and not in test for membership. x in s evaluates to True if x is a member of s , and False otherwise. x not in s returns the negation of x in s . All built-in sequences and set types support this as well as dictionary, for which in tests whether the dictionary has a given key. For container types such as list, tuple, set, frozenset, dict, or collections.deque, the expression x in y is equivalent to any(x is e or x == e for e in y) .

For the string and bytes types, x in y is True if and only if x is a substring of y . An equivalent test is y.find(x) != -1 . Empty strings are always considered to be a substring of any other string, so "" in "abc" will return True .

For user-defined classes which define the __contains__() method, x in y returns True if y.__contains__(x) returns a true value, and False otherwise.

For user-defined classes which do not define __contains__() but do define __iter__() , x in y is True if some value z , for which the expression x is z or x == z is true, is produced while iterating over y . If an exception is raised during the iteration, it is as if in raised that exception.

Lastly, the old-style iteration protocol is tried: if a class defines __getitem__() , x in y is True if and only if there is a non-negative integer index i such that x is y[i] or x == y[i] , and no lower integer index raises the IndexError exception. (If any other exception is raised, it is as if in raised that exception).

The operator not in is defined to have the inverse truth value of in .

6.10.3. Identity comparisons ¶

The operators is and is not test for an object’s identity: x is y is true if and only if x and y are the same object. An Object’s identity is determined using the id() function. x is not y yields the inverse truth value. [ 4 ]

6.11. Boolean operations ¶

In the context of Boolean operations, and also when expressions are used by control flow statements, the following values are interpreted as false: False , None , numeric zero of all types, and empty strings and containers (including strings, tuples, lists, dictionaries, sets and frozensets). All other values are interpreted as true. User-defined objects can customize their truth value by providing a __bool__() method.

The operator not yields True if its argument is false, False otherwise.

The expression x and y first evaluates x ; if x is false, its value is returned; otherwise, y is evaluated and the resulting value is returned.

The expression x or y first evaluates x ; if x is true, its value is returned; otherwise, y is evaluated and the resulting value is returned.

Note that neither and nor or restrict the value and type they return to False and True , but rather return the last evaluated argument. This is sometimes useful, e.g., if s is a string that should be replaced by a default value if it is empty, the expression s or 'foo' yields the desired value. Because not has to create a new value, it returns a boolean value regardless of the type of its argument (for example, not 'foo' produces False rather than '' .)

6.12. Assignment expressions ¶

An assignment expression (sometimes also called a “named expression” or “walrus”) assigns an expression to an identifier , while also returning the value of the expression .

One common use case is when handling matched regular expressions:

Or, when processing a file stream in chunks:

Assignment expressions must be surrounded by parentheses when used as expression statements and when used as sub-expressions in slicing, conditional, lambda, keyword-argument, and comprehension-if expressions and in assert , with , and assignment statements. In all other places where they can be used, parentheses are not required, including in if and while statements.

Added in version 3.8: See PEP 572 for more details about assignment expressions.

6.13. Conditional expressions ¶

Conditional expressions (sometimes called a “ternary operator”) have the lowest priority of all Python operations.

The expression x if C else y first evaluates the condition, C rather than x . If C is true, x is evaluated and its value is returned; otherwise, y is evaluated and its value is returned.

See PEP 308 for more details about conditional expressions.

6.14. Lambdas ¶

Lambda expressions (sometimes called lambda forms) are used to create anonymous functions. The expression lambda parameters: expression yields a function object. The unnamed object behaves like a function object defined with:

See section Function definitions for the syntax of parameter lists. Note that functions created with lambda expressions cannot contain statements or annotations.

6.15. Expression lists ¶

Except when part of a list or set display, an expression list containing at least one comma yields a tuple. The length of the tuple is the number of expressions in the list. The expressions are evaluated from left to right.

An asterisk * denotes iterable unpacking . Its operand must be an iterable . The iterable is expanded into a sequence of items, which are included in the new tuple, list, or set, at the site of the unpacking.

Added in version 3.5: Iterable unpacking in expression lists, originally proposed by PEP 448 .

A trailing comma is required only to create a one-item tuple, such as 1, ; it is optional in all other cases. A single expression without a trailing comma doesn’t create a tuple, but rather yields the value of that expression. (To create an empty tuple, use an empty pair of parentheses: () .)

6.16. Evaluation order ¶

Python evaluates expressions from left to right. Notice that while evaluating an assignment, the right-hand side is evaluated before the left-hand side.

In the following lines, expressions will be evaluated in the arithmetic order of their suffixes:

6.17. Operator precedence ¶

The following table summarizes the operator precedence in Python, from highest precedence (most binding) to lowest precedence (least binding). Operators in the same box have the same precedence. Unless the syntax is explicitly given, operators are binary. Operators in the same box group left to right (except for exponentiation and conditional expressions, which group from right to left).

Note that comparisons, membership tests, and identity tests, all have the same precedence and have a left-to-right chaining feature as described in the Comparisons section.

Operator

Description

,

, value...},

Binding or parenthesized expression, list display, dictionary display, set display

, , ,

Subscription, slicing, call, attribute reference

x

Await expression

Exponentiation 5]

, ,

Positive, negative, bitwise NOT

, , , ,

Multiplication, matrix multiplication, division, floor division, remainder 6]

,

Addition and subtraction

,

Shifts

Bitwise AND

Bitwise XOR

Bitwise OR

, in, , not, , , , , ,

Comparisons, including membership tests and identity tests

x

Boolean NOT

Boolean AND

Boolean OR

Conditional expression

Lambda expression

Assignment expression

Table of Contents

  • 6.1. Arithmetic conversions
  • 6.2.1.1. Private name mangling
  • 6.2.2. Literals
  • 6.2.3. Parenthesized forms
  • 6.2.4. Displays for lists, sets and dictionaries
  • 6.2.5. List displays
  • 6.2.6. Set displays
  • 6.2.7. Dictionary displays
  • 6.2.8. Generator expressions
  • 6.2.9.1. Generator-iterator methods
  • 6.2.9.2. Examples
  • 6.2.9.3. Asynchronous generator functions
  • 6.2.9.4. Asynchronous generator-iterator methods
  • 6.3.1. Attribute references
  • 6.3.2. Subscriptions
  • 6.3.3. Slicings
  • 6.3.4. Calls
  • 6.4. Await expression
  • 6.5. The power operator
  • 6.6. Unary arithmetic and bitwise operations
  • 6.7. Binary arithmetic operations
  • 6.8. Shifting operations
  • 6.9. Binary bitwise operations
  • 6.10.1. Value comparisons
  • 6.10.2. Membership test operations
  • 6.10.3. Identity comparisons
  • 6.11. Boolean operations
  • 6.12. Assignment expressions
  • 6.13. Conditional expressions
  • 6.14. Lambdas
  • 6.15. Expression lists
  • 6.16. Evaluation order
  • 6.17. Operator precedence

Previous topic

5. The import system

7. Simple statements

  • Report a Bug
  • Show Source

Operators and Expressions in Python

Operators and Expressions in Python

Table of Contents

Getting Started With Operators and Expressions

The assignment operator and statements, arithmetic operators and expressions in python, comparison of integer values, comparison of floating-point values, comparison of strings, comparison of lists and tuples, boolean expressions involving boolean operands, evaluation of regular objects in a boolean context, boolean expressions involving other types of operands, compound logical expressions and short-circuit evaluation, idioms that exploit short-circuit evaluation, compound vs chained expressions, conditional expressions or the ternary operator, identity operators and expressions in python, membership operators and expressions in python, concatenation and repetition operators and expressions, the walrus operator and assignment expressions, bitwise operators and expressions in python, operator precedence in python, augmented assignment operators and expressions.

In Python, operators are special symbols, combinations of symbols, or keywords that designate some type of computation. You can combine objects and operators to build expressions that perform the actual computation. So, operators are the building blocks of expressions, which you can use to manipulate your data. Therefore, understanding how operators work in Python is essential for you as a programmer.

In this tutorial, you’ll learn about the operators that Python currently supports. You’ll also learn the basics of how to use these operators to build expressions.

In this tutorial, you’ll:

  • Get to know Python’s arithmetic operators and use them to build arithmetic expressions
  • Explore Python’s comparison , Boolean , identity , and membership operators
  • Build expressions with comparison, Boolean, identity, and membership operators
  • Learn about Python’s bitwise operators and how to use them
  • Combine and repeat sequences using the concatenation and repetition operators
  • Understand the augmented assignment operators and how they work

To get the most out of this tutorial, you should have a basic understanding of Python programming concepts, such as variables , assignments , and built-in data types .

Free Bonus: Click here to download your comprehensive cheat sheet covering the various operators in Python.

Take the Quiz: Test your knowledge with our interactive “Python Operators and Expressions” quiz. You’ll receive a score upon completion to help you track your learning progress:

Interactive Quiz

Test your understanding of Python operators and expressions.

In programming, an operator is usually a symbol or combination of symbols that allows you to perform a specific operation. This operation can act on one or more operands . If the operation involves a single operand, then the operator is unary . If the operator involves two operands, then the operator is binary .

For example, in Python, you can use the minus sign ( - ) as a unary operator to declare a negative number. You can also use it to subtract two numbers:

In this code snippet, the minus sign ( - ) in the first example is a unary operator, and the number 273.15 is the operand. In the second example, the same symbol is a binary operator, and the numbers 5 and 2 are its left and right operands.

Programming languages typically have operators built in as part of their syntax. In many languages, including Python, you can also create your own operator or modify the behavior of existing ones, which is a powerful and advanced feature to have.

In practice, operators provide a quick shortcut for you to manipulate data, perform mathematical calculations, compare values, run Boolean tests, assign values to variables, and more. In Python, an operator may be a symbol, a combination of symbols, or a keyword , depending on the type of operator that you’re dealing with.

For example, you’ve already seen the subtraction operator, which is represented with a single minus sign ( - ). The equality operator is a double equal sign ( == ). So, it’s a combination of symbols:

In this example, you use the Python equality operator ( == ) to compare two numbers. As a result, you get True , which is one of Python’s Boolean values.

Speaking of Boolean values, the Boolean or logical operators in Python are keywords rather than signs, as you’ll learn in the section about Boolean operators and expressions . So, instead of the odd signs like || , && , and ! that many other programming languages use, Python uses or , and , and not .

Using keywords instead of odd signs is a really cool design decision that’s consistent with the fact that Python loves and encourages code’s readability .

You’ll find several categories or groups of operators in Python. Here’s a quick list of those categories:

  • Assignment operators
  • Arithmetic operators
  • Comparison operators
  • Boolean or logical operators
  • Identity operators
  • Membership operators
  • Concatenation and repetition operators
  • Bitwise operators

All these types of operators take care of specific types of computations and data-processing tasks. You’ll learn more about these categories throughout this tutorial. However, before jumping into more practical discussions, you need to know that the most elementary goal of an operator is to be part of an expression . Operators by themselves don’t do much:

As you can see in this code snippet, if you use an operator without the required operands, then you’ll get a syntax error . So, operators must be part of expressions, which you can build using Python objects as operands.

So, what is an expression anyway? Python has simple and compound statements. A simple statement is a construct that occupies a single logical line , like an assignment statement. A compound statement is a construct that occupies multiple logical lines, such as a for loop or a conditional statement. An expression is a simple statement that produces and returns a value.

You’ll find operators in many expressions. Here are a few examples:

In the first two examples, you use the addition and division operators to construct two arithmetic expressions whose operands are integer numbers. In the last example, you use the equality operator to create a comparison expression. In all cases, you get a specific value after executing the expression.

Note that not all expressions use operators. For example, a bare function call is an expression that doesn’t require any operator:

In the first example, you call the built-in abs() function to get the absolute value of -7 . Then, you compute 2 to the power of 8 using the built-in pow() function. These function calls occupy a single logical line and return a value. So, they’re expressions.

Finally, the call to the built-in print() function is another expression. This time, the function doesn’t return a fruitful value, but it still returns None , which is the Python null type . So, the call is technically an expression.

Note: All Python functions have a return value, either explicit or implicit. If you don’t provide an explicit return statement when defining a function, then Python will automatically make the function return None .

Even though all expressions are statements, not all statements are expressions. For example, pure assignment statements don’t return any value, as you’ll learn in a moment. Therefore, they’re not expressions. The assignment operator is a special operator that doesn’t create an expression but a statement.

Note: Since version 3.8, Python also has what it calls assignment expressions. These are special types of assignments that do return a value. You’ll learn more about this topic in the section The Walrus Operator and Assignment Expressions .

Okay! That was a quick introduction to operators and expressions in Python. Now it’s time to dive deeper into the topic. To kick things off, you’ll start with the assignment operator and statements.

The assignment operator is one of the most frequently used operators in Python. The operator consists of a single equal sign ( = ), and it operates on two operands. The left-hand operand is typically a variable , while the right-hand operand is an expression.

Note: As you already learned, the assignment operator doesn’t create an expression. Instead, it creates a statement that doesn’t return any value.

The assignment operator allows you to assign values to variables . Strictly speaking, in Python, this operator makes variables or names refer to specific objects in your computer’s memory. In other words, an assignment creates a reference to a concrete object and attaches that reference to the target variable.

Note: To dive deeper into using the assignment operator, check out Python’s Assignment Operator: Write Robust Assignments .

For example, all the statements below create new variables that hold references to specific objects:

In the first statement, you create the number variable, which holds a reference to the number 42 in your computer’s memory. You can also say that the name number points to 42 , which is a concrete object.

In the rest of the examples, you create other variables that point to other types of objects, such as a string , tuple , and list , respectively.

You’ll use the assignment operator in many of the examples that you’ll write throughout this tutorial. More importantly, you’ll use this operator many times in your own code. It’ll be your forever friend. Now you can dive into other Python operators!

Arithmetic operators are those operators that allow you to perform arithmetic operations on numeric values. Yes, they come from math, and in most cases, you’ll represent them with the usual math signs. The following table lists the arithmetic operators that Python currently supports:

Operator Type Operation Sample Expression Result
Unary Positive without any transformation since this is simply a complement to negation
Binary Addition The arithmetic sum of and
Unary Negation The value of but with the opposite sign
Binary Subtraction subtracted from
Binary Multiplication The product of and
Binary Division The quotient of divided by , expressed as a float
Binary Modulo The remainder of divided by
Binary Floor division or integer division The quotient of divided by , rounded to the next smallest whole number
Binary Exponentiation raised to the power of

Note that a and b in the Sample Expression column represent numeric values, such as integer , floating-point , complex , rational , and decimal numbers.

Here are some examples of these operators in use:

In this code snippet, you first create two new variables, a and b , holding 5 and 2 , respectively. Then you use these variables to create different arithmetic expressions using a specific operator in each expression.

Note: The Python REPL will display the return value of an expression as a way to provide immediate feedback to you. So, when you’re in an interactive session, you don’t need to use the print() function to check the result of an expression. You can just type in the expression and press Enter to get the result.

Again, the standard division operator ( / ) always returns a floating-point number, even if the dividend is evenly divisible by the divisor:

In the first example, 10 is evenly divisible by 5 . Therefore, this operation could return the integer 2 . However, it returns the floating-point number 2.0 . In the second example, 10.0 is a floating-point number, and 5 is an integer. In this case, Python internally promotes 5 to 5.0 and runs the division. The result is a floating-point number too.

Note: With complex numbers, the division operator doesn’t return a floating-point number but a complex one:

Here, you run a division between an integer and a complex number. In this case, the standard division operator returns a complex number.

Finally, consider the following examples of using the floor division ( // ) operator:

Floor division always rounds down . This means that the result is the greatest integer that’s smaller than or equal to the quotient. For positive numbers, it’s as though the fractional portion is truncated, leaving only the integer portion.

Comparison Operators and Expressions in Python

The Python comparison operators allow you to compare numerical values and any other objects that support them. The table below lists all the currently available comparison operators in Python:

Operator Operation Sample Expression Result
Equal to • if the value of is equal to the value of
• otherwise
Not equal to • if isn’t equal to
• otherwise
Less than • if is less than
• otherwise
Less than or equal to • if is less than or equal to
• otherwise
Greater than • if is greater than
• otherwise
Greater than or equal to • if is greater than or equal to
• otherwise

The comparison operators are all binary. This means that they require left and right operands. These operators always return a Boolean value ( True or False ) that depends on the truth value of the comparison at hand.

Note that comparisons between objects of different data types often don’t make sense and sometimes aren’t allowed in Python. For example, you can compare a number and a string for equality with the == operator. However, you’ll get False as a result:

The integer 2 isn’t equal to the string "2" . Therefore, you get False as a result. You can also use the != operator in the above expression, in which case you’ll get True as a result.

Non-equality comparisons between operands of different data types raise a TypeError exception:

In this example, Python raises a TypeError exception because a less than comparison ( < ) doesn’t make sense between an integer and a string. So, the operation isn’t allowed.

It’s important to note that in the context of comparisons, integer and floating-point values are compatible, and you can compare them.

You’ll typically use and find comparison operators in Boolean contexts like conditional statements and while loops . They allow you to make decisions and define a program’s control flow .

The comparison operators work on several types of operands, such as numbers, strings, tuples, and lists. In the following sections, you’ll explore the differences.

Probably, the more straightforward comparisons in Python and in math are those involving integer numbers. They allow you to count real objects, which is a familiar day-to-day task. In fact, the non-negative integers are also called natural numbers . So, comparing this type of number is probably pretty intuitive, and doing so in Python is no exception.

Consider the following examples that compare integer numbers:

In the first set of examples, you define two variables, a and b , to run a few comparisons between them. The value of a is less than the value of b . So, every comparison expression returns the expected Boolean value. The second set of examples uses two values that are equal, and again, you get the expected results.

Comparing floating-point numbers is a bit more complicated than comparing integers. The value stored in a float object may not be precisely what you’d think it would be. For that reason, it’s bad practice to compare floating-point values for exact equality using the == operator.

Consider the example below:

Yikes! The internal representation of this addition isn’t exactly equal to 3.3 , as you can see in the final example. So, comparing x to 3.3 with the equality operator returns False .

To compare floating-point numbers for equality, you need to use a different approach. The preferred way to determine whether two floating-point values are equal is to determine whether they’re close to one another, given some tolerance.

The math module from the standard library provides a function conveniently called isclose() that will help you with float comparison. The function takes two numbers and tests them for approximate equality:

In this example, you use the isclose() function to compare x and 3.3 for approximate equality. This time, you get True as a result because both numbers are close enough to be considered equal.

For further details on using isclose() , check out the Find the Closeness of Numbers With Python isclose() section in The Python math Module: Everything You Need to Know .

You can also use the comparison operators to compare Python strings in your code. In this context, you need to be aware of how Python internally compares string objects. In practice, Python compares strings character by character using each character’s Unicode code point . Unicode is Python’s default character set .

You can use the built-in ord() function to learn the Unicode code point of any character in Python. Consider the following examples:

The uppercase "A" has a lower Unicode point than the lowercase "a" . So, "A" is less than "a" . In the end, Python compares characters using integer numbers. So, the same rules that Python uses to compare integers apply to string comparison.

When it comes to strings with several characters, Python runs the comparison character by character in a loop.

The comparison uses lexicographical ordering , which means that Python compares the first item from each string. If their Unicode code points are different, this difference determines the comparison result. If the Unicode code points are equal, then Python compares the next two characters, and so on, until either string is exhausted:

In this example, Python compares both operands character by character. When it reaches the end of the string, it compares "o" and "O" . Because the lowercase letter has a greater Unicode code point, the first version of the string is greater than the second.

You can also compare strings of different lengths:

In this example, Python runs a character-by-character comparison as usual. If it runs out of characters, then the shorter string is less than the longer one. This also means that the empty string is the smallest possible string.

In your Python journey, you can also face the need to compare lists with other lists and tuples with other tuples. These data types also support the standard comparison operators. Like with strings, when you use a comparison operator to compare two lists or two tuples, Python runs an item-by-item comparison.

Note that Python applies specific rules depending on the type of the contained items. Here are some examples that compare lists and tuples of integer values:

In these examples, you compare lists and tuples of numbers using the standard comparison operators. When comparing these data types, Python runs an item-by-item comparison.

For example, in the first expression above, Python compares the 2 in the left operand and the 2 in the right operand. Because they’re equal, Python continues comparing 3 and 3 to conclude that both lists are equal. The same thing happens in the second example, where you compare tuples containing the same data.

It’s important to note that you can actually compare lists to tuples using the == and != operators. However, you can’t compare lists and tuples using the < , > , <= , and >= operators:

Python supports equality comparison between lists and tuples. However, it doesn’t support the rest of the comparison operators, as you can conclude from the final two examples. If you try to use them, then you get a TypeError telling you that the operation isn’t supported.

You can also compare lists and tuples of different lengths:

In the first two examples, you get True as a result because 5 is less than 8 . That fact is sufficient for Python to solve the comparison. In the second pair of examples, you get False . This result makes sense because the compared sequences don’t have the same length, so they can’t be equal.

In the final pair of examples, Python compares 5 with 5 . They’re equal, so the comparison continues. Because there are no more values to compare in the right-hand operands, Python concludes that the left-hand operands are greater.

As you can see, comparing lists and tuples can be tricky. It’s also an expensive operation that, in the worst case, requires traversing two entire sequences. Things get more complex and expensive when the contained items are also sequences. In those situations, Python will also have to compare items in a value-by-value manner, which adds cost to the operation.

Boolean Operators and Expressions in Python

Python has three Boolean or logical operators: and , or , and not . They define a set of operations denoted by the generic operators AND , OR , and NOT . With these operators, you can create compound conditions.

In the following sections, you’ll learn how the Python Boolean operators work. Especially, you’ll learn that some of them behave differently when you use them with Boolean values or with regular objects as operands.

You’ll find many objects and expressions that are of Boolean type or bool , as Python calls this type. In other words, many objects evaluate to True or False , which are the Python Boolean values.

For example, when you evaluate an expression using a comparison operator, the result of that expression is always of bool type:

In this example, the expression age > 18 returns a Boolean value, which you store in the is_adult variable. Now is_adult is of bool type, as you can see after calling the built-in type() function.

You can also find Python built-in and custom functions that return a Boolean value. This type of function is known as a predicate function. The built-in all() , any() , callable() , and isinstance() functions are all good examples of this practice.

Consider the following examples:

In this code snippet, you first define a variable called number using your old friend the assignment operator. Then you create another variable called validation_conditions . This variable holds a tuple of expressions. The first expression uses isinstance() to check whether number is an integer value.

The second is a compound expression that combines the modulo ( % ) and equality ( == ) operators to create a condition that checks whether the input value is an even number. In this condition, the modulo operator returns the remainder of dividing number by 2 , and the equality operator compares the result with 0 , returning True or False as the comparison’s result.

Then you use the all() function to determine if all the conditions are true. In this example, because number = 42 , the conditions are true, and all() returns True . You can play with the value of number if you’d like to experiment a bit.

In the final two examples, you use the callable() function. As its name suggests, this function allows you to determine whether an object is callable . Being callable means that you can call the object with a pair of parentheses and appropriate arguments, as you’d call any Python function.

The number variable isn’t callable, and the function returns False , accordingly. In contrast, the print() function is callable, so callable() returns True .

All the previous discussion is the basis for understanding how the Python logical operators work with Boolean operands.

Logical expressions involving and , or , and not are straightforward when the operands are Boolean. Here’s a summary. Note that x and y represent Boolean operands:

Operator Sample Expression Result
• if both and are
• otherwise
• if either or is
• otherwise
• if is
• if is

This table summarizes the truth value of expressions that you can create using the logical operators with Boolean operands. There’s something to note in this summary. Unlike and and or , which are binary operators, the not operator is unary, meaning that it operates on one operand. This operand must always be on the right side.

Now it’s time to take a look at how the operators work in practice. Here are a few examples of using the and operator with Boolean operands:

In the first example, both operands return True . Therefore, the and expression returns True as a result. In the second example, the left-hand operand is True , but the right-hand operand is False . Because of this, the and operator returns False .

In the third example, the left-hand operand is False . In this case, the and operator immediately returns False and never evaluates the 3 == 3 condition. This behavior is called short-circuit evaluation . You’ll learn more about it in a moment.

Note: Short-circuit evaluation is also called McCarthy evaluation in honor of computer scientist John McCarthy .

In the final example, both conditions return False . Again, and returns False as a result. However, because of the short-circuit evaluation, the right-hand expression isn’t evaluated.

What about the or operator? Here are a few examples that demonstrate how it works:

In the first three examples, at least one of the conditions returns True . In all cases, the or operator returns True . Note that if the left-hand operand is True , then or applies short-circuit evaluation and doesn’t evaluate the right-hand operand. This makes sense. If the left-hand operand is True , then or already knows the final result. Why would it need to continue the evaluation if the result won’t change?

In the final example, both operands are False , and this is the only situation where or returns False . It’s important to note that if the left-hand operand is False , then or has to evaluate the right-hand operand to arrive at a final conclusion.

Finally, you have the not operator, which negates the current truth value of an object or expression:

If you place not before an expression, then you get the inverse truth value. When the expression returns True , you get False . When the expression evaluates to False , you get True .

There is a fundamental behavior distinction between not and the other two Boolean operators. In a not expression, you always get a Boolean value as a result. That’s not always the rule that governs and and or expressions, as you’ll learn in the Boolean Expressions Involving Other Types of Operands section.

In practice, most Python objects and expressions aren’t Boolean. In other words, most objects and expressions don’t have a True or False value but a different type of value. However, you can use any Python object in a Boolean context, such as a conditional statement or a while loop.

In Python, all objects have a specific truth value. So, you can use the logical operators with all types of operands.

Python has well-established rules to determine the truth value of an object when you use that object in a Boolean context or as an operand in an expression built with logical operators. Here’s what the documentation says about this topic:

By default, an object is considered true unless its class defines either a __bool__() method that returns False or a __len__() method that returns zero, when called with the object. Here are most of the built-in objects considered false: constants defined to be false: None and False . zero of any numeric type: 0 , 0.0 , 0j , Decimal(0) , Fraction(0, 1) empty sequences and collections: '' , () , [] , {} , set() , range(0) ( Source )

You can determine the truth value of an object by calling the built-in bool() function with that object as an argument. If bool() returns True , then the object is truthy . If bool() returns False , then it’s falsy .

For numeric values, you have that a zero value is falsy, while a non-zero value is truthy:

Python considers the zero value of all numeric types falsy. All the other values are truthy, regardless of how close to zero they are.

Note: Instead of a function, bool() is a class. However, because Python developers typically use this class as a function, you’ll find that most people refer to it as a function rather than as a class. Additionally, the documentation lists this class on the built-in functions page. This is one of those cases where practicality beats purity .

When it comes to evaluating strings, you have that an empty string is always falsy, while a non-empty string is truthy:

Note that strings containing white spaces are also truthy in Python’s eyes. So, don’t confuse empty strings with whitespace strings.

Finally, built-in container data types, such as lists, tuples, sets , and dictionaries , are falsy when they’re empty. Otherwise, Python considers them truthy objects:

To determine the truth value of container data types, Python relies on the .__len__() special method . This method provides support for the built-in len() function, which you can use to determine the number of items in a given container.

In general, if .__len__() returns 0 , then Python considers the container a falsy object, which is consistent with the general rules you’ve just learned before.

All the discussion about the truth value of Python objects in this section is key to understanding how the logical operators behave when they take arbitrary objects as operands.

You can also use any objects, such as numbers or strings, as operands to and , or , and not . You can even use combinations of a Boolean object and a regular one. In these situations, the result depends on the truth value of the operands.

Note: Boolean expressions that combine two Boolean operands are a special case of a more general rule that allows you to use the logical operators with all kinds of operands. In every case, you’ll get one of the operands as a result.

You’ve already learned how Python determines the truth value of objects. So, you’re ready to dive into creating expressions with logic operators and regular objects.

To start off, below is a table that summarizes what you get when you use two objects, x and y , in an and expression:

If is returns
Truthy
Falsy

It’s important to emphasize a subtle detail in the above table. When you use and in an expression, you don’t always get True or False as a result. Instead, you get one of the operands. You only get True or False if the returned operand has either of these values.

Here are some code examples that use integer values. Remember that in Python, the zero value of numeric types is falsy. The rest of the values are truthy:

In the first expression, the left-hand operand ( 3 ) is truthy. So, you get the right-hand operand ( 4 ) as a result.

In the second example, the left-hand operand ( 0 ) is falsy, and you get it as a result. In this case, Python applies the short-circuit evaluation technique. It already knows that the whole expression is false because 0 is falsy, so Python returns 0 immediately without evaluating the right-hand operand.

In the final expression, the left-hand operand ( 3 ) is truthy. Therefore Python needs to evaluate the right-hand operand to make a conclusion. As a result, you get the right-hand operand, no matter what its truth value is.

Note: To dive deeper into the and operator, check out Using the “and” Boolean Operator in Python .

When it comes to using the or operator, you also get one of the operands as a result. This is what happens for two arbitrary objects, x and y :

Again, the expression x or y doesn’t evaluate to either True or False . Instead, it returns one of its operands, x or y .

As you can conclude from the above table, if the left-hand operand is truthy, then you get it as a result. Otherwise, you get the second operand. Here are some examples that demonstrate this behavior:

In the first example, the left-hand operand is truthy, and or immediately returns it. In this case, Python doesn’t evaluate the second operand because it already knows the final result. In the second example, the left-hand operand is falsy, and Python has to evaluate the right-hand one to determine the result.

In the last example, the left-hand operand is truthy, and that fact defines the result of the expression. There’s no need to evaluate the right-hand operand.

An expression like x or y is truthy if either x or y is truthy, and falsy if both x and y are falsy. This type of expression returns the first truthy operand that it finds. If both operands are falsy, then the expression returns the right-hand operand. To see this latter behavior in action, consider the following example:

In this specific expression, both operands are falsy. So, the or operator returns the right-hand operand, and the whole expression is falsy as a result.

Note: To learn more about the or operator, check out Using the “or” Boolean Operator in Python .

Finally, you have the not operator. You can also use this one with any object as an operand. Here’s what happens:

The not operator has a uniform behavior. It always returns a Boolean value. This behavior differs from its sibling operators, and and or .

Here are some code examples:

In the first example, the operand, 3 , is truthy from Python’s point of view. So, the operator returns False . In the second example, the operand is falsy, and not returns True .

Note: To better understand the not operator, check out Using the “not” Boolean Operator in Python .

In summary, the Python not operator negates the truth value of an object and always returns a Boolean value. This latter behavior differs from the behavior of its sibling operators and and or , which return operands rather than Boolean values.

So far, you’ve seen expressions with only a single or or and operator and two operands. However, you can also create compound logical expressions with multiple logical operators and operands.

To illustrate how to create a compound expression using or , consider the following toy example:

This expression returns the first truthy value. If all the preceding x variables are falsy, then the expression returns the last value, xn .

Note: In an expression like the one above, Python uses short-circuit evaluation . The operands are evaluated in order from left to right. As soon as one is found to be true, the entire expression is known to be true. At that point, Python stops evaluating operands. The value of the entire expression is that of the x that terminates the evaluation.

To help demonstrate short-circuit evaluation, suppose that you have an identity function , f() , that behaves as follows:

  • Takes a single argument
  • Displays the function and its argument on the screen
  • Returns the argument as its return value

Here’s the code to define this function and also a few examples of how it works:

The f() function displays its argument, which visually confirms whether you called the function. It also returns the argument as you passed it in the call. Because of this behavior, you can make the expression f(arg) be truthy or falsy by specifying a value for arg that’s truthy or falsy, respectively.

Now, consider the following compound logical expression:

In this example, Python first evaluates f(0) , which returns 0 . This value is falsy. The expression isn’t true yet, so the evaluation continues from left to right. The next operand, f(False) , returns False . That value is also falsy, so the evaluation continues.

Next up is f(1) . That evaluates to 1 , which is truthy. At that point, Python stops the evaluation because it already knows that the entire expression is truthy. Consequently, Python returns 1 as the value of the expression and never evaluates the remaining operands, f(2) and f(3) . You can confirm from the output that the f(2) and f(3) calls don’t occur.

A similar behavior appears in an expression with multiple and operators like the following one:

This expression is truthy if all the operands are truthy. If at least one operand is falsy, then the expression is also falsy.

In this example, short-circuit evaluation dictates that Python stops evaluating as soon as an operand happens to be falsy. At that point, the entire expression is known to be false. Once that’s the case, Python stops evaluating operands and returns the falsy operand that terminated the evaluation.

Here are two examples that confirm the short-circuiting behavior:

In both examples, the evaluation stops at the first falsy term— f(False) in the first case, f(0.0) in the second case—and neither the f(2) nor the f(3) call occurs. In the end, the expressions return False and 0.0 , respectively.

If all the operands are truthy, then Python evaluates them all and returns the last (rightmost) one as the value of the expression:

In the first example, all the operands are truthy. The expression is also truthy and returns the last operand. In the second example, all the operands are truthy except for the last one. The expression is falsy and returns the last operand.

As you dig into Python, you’ll find that there are some common idiomatic patterns that exploit short-circuit evaluation for conciseness of expression, performance, and safety. For example, you can take advantage of this type of evaluation for:

  • Avoiding an exception
  • Providing a default value
  • Skipping a costly operation

To illustrate the first point, suppose you have two variables, a and b , and you want to know whether the division of b by a results in a number greater than 0 . In this case, you can run the following expression or condition:

This code works. However, you need to account for the possibility that a might be 0 , in which case you’ll get an exception :

In this example, the divisor is 0 , which makes Python raise a ZeroDivisionError exception. This exception breaks your code. You can skip this error with an expression like the following:

When a is 0 , a != 0 is false. Python’s short-circuit evaluation ensures that the evaluation stops at that point, which means that (b / a) never runs, and the error never occurs.

Using this technique, you can implement a function to determine whether an integer is divisible by another integer:

In this function, if b is 0 , then a / b isn’t defined. So, the numbers aren’t divisible. If b is different from 0 , then the result will depend on the remainder of the division.

Selecting a default value when a specified value is falsy is another idiom that takes advantage of the short-circuit evaluation feature of Python’s logical operators.

For example, say that you have a variable that’s supposed to contain a country’s name. At some point, this variable can end up holding an empty string. If that’s the case, then you’d like the variable to hold a default county name. You can also do this with the or operator:

If country is non-empty, then it’s truthy. In this scenario, the expression will return the first truthy value, which is country in the first or expression. The evaluation stops, and you get "Canada" as a result.

On the other hand, if country is an empty string , then it’s falsy. The evaluation continues to the next operand, default_country , which is truthy. Finally, you get the default country as a result.

Another interesting use case for short-circuit evaluation is to avoid costly operations while creating compound logical expressions. For example, if you have a costly operation that should only run if a given condition is false, then you can use or like in the following snippet:

In this construct, your clean_data() function represents a costly operation. Because of short-circuit evaluation, this function will only run when data_is_clean is false, which means that your data isn’t clean.

Another variation of this technique is when you want to run a costly operation if a given condition is true. In this case, you can use the and operator:

In this example, the and operator evaluates data_is_updated . If this variable is true, then the evaluation continues, and the process_data() function runs. Otherwise, the evaluation stops, and process_data() never runs.

Sometimes you have a compound expression that uses the and operator to join comparison expressions. For example, say that you want to determine if a number is in a given interval. You can solve this problem with a compound expression like the following:

In this example, you use the and operator to join two comparison expressions that allow you to find out if number is in the interval from 0 to 10 , both included.

In Python, you can make this compound expression more concise by chaining the comparison operators together. For example, the following chained expression is equivalent to the previous compound one:

This expression is more concise and readable than the original expression. You can quickly realize that this code is checking if the number is between 0 and 10 . Note that in most programming languages, this chained expression doesn’t make sense. In Python, it works like a charm.

In other programming languages, this expression would probably start by evaluating 0 <= number , which is true. This true value would then be compared with 10 , which doesn’t make much sense, so the expression fails.

Python internally processes this type of expression as an equivalent and expression, such as 0 <= number and number <= 10 . That’s why you get the correct result in the example above.

Python has what it calls conditional expressions . These kinds of expressions are inspired by the ternary operator that looks like a ? b : c and is used in other programming languages. This construct evaluates to b if the value of a is true, and otherwise evaluates to c . Because of this, sometimes the equivalent Python syntax is also known as the ternary operator.

However, in Python, the expression looks more readable:

This expression returns expression_1 if the condition is true and expression_2 otherwise. Note that this expression is equivalent to a regular conditional like the following:

So, why does Python need this syntax? PEP 308 introduced conditional expressions as an effort to avoid the prevalence of error-prone attempts to achieve the same effect of a traditional ternary operator using the and and or operators in an expression like the following:

However, this expression doesn’t work as expected, returning expression_2 when expression_1 is falsy.

Some Python developers would avoid the syntax of conditional expressions in favor of a regular conditional statement. In any case, this syntax can be handy in some situations because it provides a concise tool for writing two-way conditionals.

Here’s an example of how to use the conditional expression syntax in your code:

When day is equal to "Sunday" , the condition is true and you get the first expression, "11AM" , as a result. If the condition is false, then you get the second expression, "9AM" . Note that similarly to the and and or operators, the conditional expression returns the value of one of its expressions rather than a Boolean value.

Python provides two operators, is and is not , that allow you to determine whether two operands have the same identity . In other words, they let you check if the operands refer to the same object. Note that identity isn’t the same thing as equality. The latter aims to check whether two operands contain the same data.

Note: To learn more about the difference between identity and equality, check out Python ‘!=’ Is Not ‘is not’: Comparing Objects in Python .

Here’s a summary of Python’s identity operators. Note that x and y are variables that point to objects:

Operator Sample Expression Result
• if and hold a reference to the same in-memory object
• otherwise
• if points to an object different from the object that points to
• otherwise

These two Python operators are keywords instead of odd symbols. This is part of Python’s goal of favoring readability in its syntax.

Here’s an example of two variables, x and y , that refer to objects that are equal but not identical:

In this example, x and y refer to objects whose value is 1001 . So, they’re equal. However, they don’t reference the same object. That’s why the is operator returns False . You can check an object’s identity using the built-in id() function:

As you can conclude from the id() output, x and y don’t have the same identity. So, they’re different objects, and because of that, the expression x is y returns False . In other words, you get False because you have two different instances of 1001 stored in your computer’s memory.

When you make an assignment like y = x , Python creates a second reference to the same object. Again, you can confirm that with the id() function or the is operator:

In this example, a and b hold references to the same object, the string "Hello, Pythonista!" . Therefore, the id() function returns the same identity when you call it with a and b . Similarly, the is operator returns True .

Note: You should note that, on your computer, you’ll get a different identity number when you call id() in the example above. The key detail is that the identity number will be the same for a and b .

Finally, the is not operator is the opposite of is . So, you can use is not to determine if two names don’t refer to the same object:

In the first example, because x and y point to different objects in your computer’s memory, the is not operator returns True . In the second example, because a and b are references to the same object, the is not operator returns False .

Note: The syntax not x is y also works the same as x is not y . However, the former syntax looks odd and is difficult to read. That’s why Python recognizes is not as an operator and encourages its use for readability.

Again, the is not operator highlights Python’s readability goals. In general, both identity operators allow you to write checks that read as plain English.

Sometimes you need to determine whether a value is present in a container data type, such as a list, tuple, or set. In other words, you may need to check if a given value is or is not a member of a collection of values. Python calls this kind of check a membership test .

Note: For a deep dive into how Python’s membership tests work, check out Python’s “in” and “not in” Operators: Check for Membership .

Membership tests are quite common and useful in programming. As with many other common operations, Python has dedicated operators for membership tests. The table below lists the membership operators in Python:

Operator Sample Expression Result
• if present in
• otherwise
• if present in of values
• otherwise

As usual, Python favors readability by using English words as operators instead of potentially confusing symbols or combinations of symbols.

Note: The syntax not value in collection also works in Python. However, this syntax looks odd and is difficult to read. So, to keep your code clean and readable, you should use value not in collection , which almost reads as plain English.

The Python in and not in operators are binary. This means that you can create membership expressions by connecting two operands with either operator. However, the operands in a membership expression have particular characteristics:

  • Left operand : The value that you want to look for in a collection of values
  • Right operand : The collection of values where the target value may be found

To better understand the in operator, below you have two demonstrative examples consisting of determining whether a value is in a list:

The first expression returns True because 5 is in the list of numbers. The second expression returns False because 8 isn’t in the list.

The not in membership operator runs the opposite test as the in operator. It allows you to check whether an integer value is not in a collection of values:

In the first example, you get False because 5 is in the target list. In the second example, you get True because 8 isn’t in the list of values. This may sound like a tongue twister because of the negative logic. To avoid confusion, remember that you’re trying to determine if the value is not part of a given collection of values.

There are two operators in Python that acquire a slightly different meaning when you use them with sequence data types, such as lists, tuples, and strings. With these types of operands, the + operator defines a concatenation operator , and the * operator represents the repetition operator :

Operator Operation Sample Expression Result
Concatenation A new sequence containing all the items from both operands
Repetition A new sequence containing the items of repeated times

Both operators are binary. The concatenation operator takes two sequences as operands and returns a new sequence of the same type. The repetition operator takes a sequence and an integer number as operands. Like in regular multiplication, the order of the operands doesn’t alter the repetition’s result.

Note: To learn more about concatenating string objects, check out Efficient String Concatenation in Python .

Here are some examples of how the concatenation operator works in practice:

In the first example, you use the concatenation operator ( + ) to join two strings together. The operator returns a completely new string object that combines the two original strings.

In the second example, you concatenate two tuples of letters together. Again, the operator returns a new tuple object containing all the items from the original operands. In the final example, you do something similar but this time with two lists.

Note: To learn more about concatenating lists, check out the Concatenating Lists section in the tutorial Python’s list Data Type: A Deep Dive With Examples .

When it comes to the repetition operator, the idea is to repeat the content of a given sequence a certain number of times. Here are a few examples:

In the first example, you use the repetition operator ( * ) to repeat the "Hello" string three times. In the second example, you change the order of the operands by placing the integer number on the left and the target string on the right. This example shows that the order of the operands doesn’t affect the result.

The next examples use the repetition operators with a tuple and a list, respectively. In both cases, you get a new object of the same type containing the items in the original sequence repeated three times.

Regular assignment statements with the = operator don’t have a return value, as you already learned. Instead, the assignment operator creates or updates variables. Because of this, the operator can’t be part of an expression.

Since Python 3.8 , you have access to a new operator that allows for a new type of assignment. This new assignment is called assignment expression or named expression . The new operator is called the walrus operator , and it’s the combination of a colon and an equal sign ( := ).

Note: The name walrus comes from the fact that this operator resembles the eyes and tusks of a walrus lying on its side. For a deep dive into how this operator works, check out The Walrus Operator: Python’s Assignment Expressions .

Unlike regular assignments, assignment expressions do have a return value, which is why they’re expressions . So, the operator accomplishes two tasks:

  • Returns the expression’s result
  • Assigns the result to a variable

The walrus operator is also a binary operator. Its left-hand operand must be a variable name, and its right-hand operand can be any Python expression. The operator will evaluate the expression, assign its value to the target variable, and return the value.

The general syntax of an assignment expression is as follows:

This expression looks like a regular assignment. However, instead of using the assignment operator ( = ), it uses the walrus operator ( := ). For the expression to work correctly, the enclosing parentheses are required in most use cases. However, in certain situations, you won’t need them. Either way, they won’t hurt you, so it’s safe to use them.

Assignment expressions come in handy when you want to reuse the result of an expression or part of an expression without using a dedicated assignment to grab this value beforehand. It’s particularly useful in the context of a conditional statement. To illustrate, the example below shows a toy function that checks the length of a string object:

In this example, you use a conditional statement to check whether the input string has fewer than 8 characters.

The assignment expression, (n := len(string)) , computes the string length and assigns it to n . Then it returns the value that results from calling len() , which finally gets compared with 8 . This way, you guarantee that you have a reference to the string length to use in further operations.

Bitwise operators treat operands as sequences of binary digits and operate on them bit by bit. Currently, Python supports the following bitwise operators:

Operator Operation Sample Expression Result
Bitwise AND • Each bit position in the result is the logical AND of the bits in the corresponding position of the operands.
• if both bits are , otherwise .
Bitwise OR • Each bit position in the result is the logical of the bits in the corresponding position of the operands.
• if either bit is , otherwise .
Bitwise NOT • Each bit position in the result is the logical negation of the bit in the corresponding position of the operand.
• if the bit is and if the bit is .
Bitwise XOR (exclusive OR) • Each bit position in the result is the logical of the bits in the corresponding position of the operands.
• if the bits in the operands are different, if they’re equal.
Bitwise right shift Each bit is shifted right places.
Bitwise left shift Each bit is shifted left places.

As you can see in this table, most bitwise operators are binary, which means that they expect two operands. The bitwise NOT operator ( ~ ) is the only unary operator because it expects a single operand, which should always appear at the right side of the expression.

You can use Python’s bitwise operators to manipulate your data at its most granular level, the bits. These operators are commonly useful when you want to write low-level algorithms, such as compression, encryption, and others.

Note: For a deep dive into the bitwise operators, check out Bitwise Operators in Python . You can also check out Build a Maze Solver in Python Using Graphs for an example of using bitwise operators to construct a binary file format.

Here are some examples that illustrate how some of the bitwise operators work in practice:

In the first example, you use the bitwise AND operator. The commented lines begin with # and provide a visual representation of what happens at the bit level. Note how each bit in the result is the logical AND of the bits in the corresponding position of the operands.

The second example shows how the bitwise OR operator works. In this case, the resulting bits are the logical OR test of the corresponding bits in the operands.

In all the examples, you’ve used the built-in bin() function to display the result as a binary object. If you don’t wrap the expression in a call to bin() , then you’ll get the integer representation of the output.

Up to this point, you’ve coded sample expressions that mostly use one or two different types of operators. However, what if you need to create compound expressions that use several different types of operators, such as comparison, arithmetic, Boolean, and others? How does Python decide which operation runs first?

Consider the following math expression:

There might be ambiguity in this expression. Should Python perform the addition 20 + 4 first and then multiply the result by 10 ? Should Python run the multiplication 4 * 10 first, and the addition second?

Because the result is 60 , you can conclude that Python has chosen the latter approach. If it had chosen the former, then the result would be 240 . This follows a standard algebraic rule that you’ll find in virtually all programming languages.

All operators that Python supports have a precedence compared to other operators. This precedence defines the order in which Python runs the operators in a compound expression.

In an expression, Python runs the operators of highest precedence first. After obtaining those results, Python runs the operators of the next highest precedence. This process continues until the expression is fully evaluated. Any operators of equal precedence are performed in left-to-right order.

Here’s the order of precedence of the Python operators that you’ve seen so far, from highest to lowest:

Operators Description
Exponentiation
, , Unary positive, unary negation, bitwise negation
, , , Multiplication, division, floor division,
, Addition, subtraction
, Bitwise shifts
Bitwise AND
Bitwise XOR
Bitwise OR
, , , , , , , , , Comparisons, identity, and membership
Boolean NOT
Boolean AND
Boolean OR
Walrus

Operators at the top of the table have the highest precedence, and those at the bottom of the table have the lowest precedence. Any operators in the same row of the table have equal precedence.

Getting back to your initial example, Python runs the multiplication because the multiplication operator has a higher precedence than the addition one.

Here’s another illustrative example:

In the example above, Python first raises 3 to the power of 4 , which equals 81 . Then, it carries out the multiplications in order from left to right: 2 * 81 = 162 and 162 * 5 = 810 .

You can override the default operator precedence using parentheses to group terms as you do in math. The subexpressions in parentheses will run before expressions that aren’t in parentheses.

Here are some examples that show how a pair of parentheses can affect the result of an expression:

In the first example, Python computes the expression 20 + 4 first because it’s wrapped in parentheses. Then Python multiplies the result by 10 , and the expression returns 240 . This result is completely different from what you got at the beginning of this section.

In the second example, Python evaluates 4 * 5 first. Then it raises 3 to the power of the resulting value. Finally, Python multiplies the result by 2 , returning 6973568802 .

There’s nothing wrong with making liberal use of parentheses, even when they aren’t necessary to change the order of evaluation. Sometimes it’s a good practice to use parentheses because they can improve your code’s readability and relieve the reader from having to recall operator precedence from memory.

Consider the following example:

Here the parentheses are unnecessary, as the comparison operators have higher precedence than and . However, some might find the parenthesized version clearer than the version without parentheses:

On the other hand, some developers might prefer this latter version of the expression. It’s a matter of personal preference. The point is that you can always use parentheses if you feel that they make your code more readable, even if they aren’t necessary to change the order of evaluation.

So far, you’ve learned that a single equal sign ( = ) represents the assignment operator and allows you to assign a value to a variable. Having a right-hand operand that contains other variables is perfectly valid, as you’ve also learned. In particular, the expression to the right of the assignment operator can include the same variable that’s on the left of the operand.

That last sentence may sound confusing, so here’s an example that clarifies the point:

In this example, total is an accumulator variable that you use to accumulate successive values. You should read this example as total is equal to the current value of total plus 5 . This expression effectively increases the value of total , which is now 15 .

Note that this type of assignment only makes sense if the variable in question already has a value. If you try the assignment with an undefined variable, then you get an error:

In this example, the count variable isn’t defined before the assignment, so it doesn’t have a current value. In consequence, Python raises a NameError exception to let you know about the issue.

This type of assignment helps you create accumulators and counter variables, for example. Therefore, it’s quite a common task in programming. As in many similar cases, Python offers a more convenient solution. It supports a shorthand syntax called augmented assignment :

In the highlighted line, you use the augmented addition operator ( += ). With this operator, you create an assignment that’s fully equivalent to total = total + 5 .

Python supports many augmented assignment operators. In general, the syntax for this type of assignment looks something like this:

Note that the dollar sign ( $ ) isn’t a valid Python operator. In this example, it’s a placeholder for a generic operator. The above statement works as follows:

  • Evaluate expression to produce a value.
  • Run the operation defined by the operator that prefixes the assignment operator ( = ), using the current value of variable and the return value of expression as operands.
  • Assign the resulting value back to variable .

The table below shows a summary of the augmented operators for arithmetic operations:

Operator Description Sample Expression Equivalent Expression
Adds the right operand to the left operand and stores the result in the left operand
Subtracts the right operand from the left operand and stores the result in the left operand
Multiplies the right operand with the left operand and stores the result in the left operand
Divides the left operand by the right operand and stores the result in the left operand
Performs of the left operand by the right operand and stores the result in the left operand
Finds the remainder of dividing the left operand by the right operand and stores the result in the left operand
Raises the left operand to the power of the right operand and stores the result in the left operand

As you can conclude from this table, all the arithmetic operators have an augmented version in Python. You can use these augmented operators as a shortcut when creating accumulators, counters, and similar objects.

Did the augmented arithmetic operators look neat and useful to you? The good news is that there are more. You also have augmented bitwise operators in Python:

Operator Operation Example Equivalent
Augmented bitwise AND ( )
Augmented bitwise OR ( )
Augmented bitwise XOR ( )
Augmented bitwise right shift
Augmented bitwise left shift

Finally, the concatenation and repetition operators have augmented variations too. These variations behave differently with mutable and immutable data types:

Operator Description Example
• Runs an augmented concatenation operation on the target sequence.
• Mutable sequences are updated in place.
• If the sequence is immutable, then a new sequence is created and assigned back to the target name.
• Adds to itself times.
• Mutable sequences are updated in place.
• If the sequence is immutable, then a new sequence is created and assigned back to the target name.

Note that the augmented concatenation operator works on two sequences, while the augmented repetition operator works on a sequence and an integer number.

Now you know what operators Python supports and how to use them. Operators are symbols, combinations of symbols, or keywords that you can use along with Python objects to build different types of expressions and perform computations in your code.

In this tutorial, you’ve learned:

  • What Python’s arithmetic operators are and how to use them in arithmetic expressions
  • What Python’s comparison , Boolean , identity , membership operators are
  • How to write expressions using comparison, Boolean, identity, and membership operators
  • Which bitwise operators Python supports and how to use them
  • How to combine and repeat sequences using the concatenation and repetition operators
  • What the augmented assignment operators are and how they work

In other words, you’ve covered an awful lot of ground! If you’d like a handy cheat sheet that can jog your memory on all that you’ve learned, then click the link below:

With all this knowledge about operators, you’re better prepared as a Python developer. You’ll be able to write better and more robust expressions in your code.

🐍 Python Tricks 💌

Get a short & sweet Python Trick delivered to your inbox every couple of days. No spam ever. Unsubscribe any time. Curated by the Real Python team.

Python Tricks Dictionary Merge

About Leodanis Pozo Ramos

Leodanis Pozo Ramos

Leodanis is an industrial engineer who loves Python and software development. He's a self-taught Python developer with 6+ years of experience. He's an avid technical writer with a growing number of articles published on Real Python and other sites.

Each tutorial at Real Python is created by a team of developers so that it meets our high quality standards. The team members who worked on this tutorial are:

Dan Bader

Master Real-World Python Skills With Unlimited Access to Real Python

Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas:

Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas:

What Do You Think?

What’s your #1 takeaway or favorite thing you learned? How are you going to put your newfound skills to use? Leave a comment below and let us know.

Commenting Tips: The most useful comments are those written with the goal of learning from or helping out other students. Get tips for asking good questions and get answers to common questions in our support portal . Looking for a real-time conversation? Visit the Real Python Community Chat or join the next “Office Hours” Live Q&A Session . Happy Pythoning!

Keep Learning

Related Topics: basics python

Related Tutorials:

  • Strings and Character Data in Python
  • Conditional Statements in Python
  • Basic Data Types in Python: A Quick Exploration
  • Lists vs Tuples in Python
  • Python Program Lexical Structure

Keep reading Real Python by creating a free account or signing in:

Already have an account? Sign-In

Almost there! Complete this form and click the button below to gain instant access:

Operators and Expressions in Python (Cheat Sheet)

🔒 No spam. We take your privacy seriously.

python assignment conditional

  • Conditionals  > 

Conditionals Practice

Let’s try some simple practice problems. These problems are not graded - they are just for you to practice before doing the real exercises in the lab itself. You can find the answers below each question by clicking the button below each question.

4.5 Reading Code

Consider the following Python program:

What output is printed when the user inputs the values $ 2 $ and $ 4 $ ?

This program will produce the following output:

This is because $ 2 + 4 \text{ % } 3 == 0 $ is True , but $ 4 + 12 \text{ % } 3 == 0 $ is False .

4.6 Testing Code

Consider the program in the previous question. Write a set of possible inputs to the program that will achieve path coverage . For each set of inputs, identify which branches will be executed when that input is provided to the program.

Think carefully! The same if statement is executed twice with different values, but those values are related to each other.

To achieve path coverage, the following inputs can be used:

There are many other possible answers to this question!

4.7 Reading Code

What output is displayed when the user inputs the values $ 4 $ and $ 29 $ ?

The program will produce this output:

This is because $ 4 * 5 > 29 $ is False , but $ 29 % 5 = 4 $ is True .

4.8 Testing Code

4.9 writing code.

Write a complete Python that performs the following actions:

  • Accept a single input from the user and convert it to an integer
  • If the number is even, display “That is an even number”. If it is odd, display “That is an odd number”.
  • If the number is negative, display “That is a negative number”. If it is zero or positive, display “That is a positive number”.

Your program should include at least two conditional statements.

One possible answer is given below:

4.10 Writing Code

Write a complete Python program in that file that performs the following actions:

  • Accept a single string as input from the user
  • If the string comes before the string “First” in lexicographic order, print “That comes before First”. If not, print “That comes after First”.
  • If the string comes after the string “last” in lexicographic order, print “That comes after last”. If not, print “That comes before last”.

Recall that you can use Boolean comparators such as < and > to compare two strings in Python. Also, pay special attention to the capitalization of the words “First” and “last” in the description above.

Bonus food for thought: look at your completed answer - is there a path that is not possible to actually test? Why is that?

Notice that it is impossible to provide an input that will come before the string "First" and after the string "last" - therefore one of the four possible paths in this program is impossible to test. In a future lab, we’ll see how we can combine these statements in a way that they won’t include any impossible paths.

Last modified by: Russell Feldhausen May 25, 2023

  • Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand
  • OverflowAI GenAI features for Teams
  • OverflowAPI Train & fine-tune LLMs
  • Labs The future of collective knowledge sharing
  • About the company Visit the blog

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Get early access and see previews of new features.

Assign within if statement Python

Is there a simpler alternative than

One which combines the assignment and if conditional into one statement?

  • if-statement

Peter's user avatar

  • The first way you have is fine. Just be sure to use if res is None if the returned value can be some other valid but falsey values (e.g. empty string). –  wim Commented May 6, 2015 at 2:52
  • What you're really looking for here is C-style if res=spam(): or if (ch=getch()) != EOF: , and Python doesn't have that. Python has good reasons for that; Swift has different good reasons for it; if you're designing a new language and, saving one line or 5 characters may well be worth if it there are no compelling reasons otherwise, but you may have compelling reasons otherwise. –  abarnert Commented May 8, 2015 at 22:00

2 Answers 2

For Python 3.8+, PEP 572 introduces Assignment Expressions

This allows assigning to variables within an expression using the notation NAME := expr . It can be used within if statements, for example:

mhudnell's user avatar

  • 3 You forgot to mention the informal name given to this new operator, the "walrus operator". –  Mark Ransom Commented Jul 23, 2021 at 18:53
  • this assigns match to the result of pattern.search(data). Would you be able to assign match to data in one line? –  Vincent Commented Feb 7, 2023 at 8:45

Often, what you have is already the best option.

You can always create a new scope to bind the value to a variable:

But that's certainly not going to be more readable, or more Pythonic.

If you just want to save one line, you can do this:

This is sometimes more readable, but usually it's a net loss.

Another way to deal with this would be to change do_something_with to accept None and do nothing. This isn't as common in Python as it is in, say, Smalltalk or Swift, but it definitely has its place sometimes.

It's hard to see why with a toy example like this, but if you're calling these functions 70 times, putting the check in one place, inside the function, instead of in 70 places, everywhere it's called, is an obvious win. (Especially since you'd probably put it in 68 places and forget the other 2.)

Last, but not least, in many cases the right answer is exceptions. Your do_something_with probably already raises if you pass None . And you could surely change returns_value_or_none to returns_value_or_raises .

Again, in this toy example, it'll just look like more code. But in real-life code, it often makes sense to put a whole block of code inside a try / except , and handle all the errors at once down at the end. Or even to let the exceptions percolate up to a higher level where they're easier to deal with.

Of course that isn't appropriate in every case; if you're expecting None to be a frequent and perfectly reasonable response, and just want to skip one step rather than abort the whole chain of operations, checking or passing through None is going to make a lot more sense than littering your code with small try blocks.

abarnert's user avatar

  • Thanks, I guess I was optimistic about some syntactic sugar. The problem with allowing the called functions to take None is that, in other contexts, I want the same function to raise an error if None or another invalid type is received. Plus, in most cases, it's something like if re.match(some_pattern, text): do_something_with(re.match(some_pattern, text).group(1)) . If forget the if condition and re.match() returns None the interpreter will let me know soon enough. –  Peter Commented May 8, 2015 at 21:49
  • @Peter: Usually there's nothing wrong with letting the interpreter let you know (whether "you" means the except handler in your code, or the programmer who didn't consider the possibility that the value could be None and therefore didn't code for it). –  abarnert Commented May 8, 2015 at 21:56
  • @Peter: Meanwhile, if you only show us a meaningless toy example, you're only going to get "here are a half-dozen ways to do similar things; which one is appropriate in your real code depends on that real code"; if you show us a couple of real examples, we can show you the idiomatic way to deal with those examples. –  abarnert Commented May 8, 2015 at 22:01

Your Answer

Reminder: Answers generated by artificial intelligence tools are not allowed on Stack Overflow. Learn more

Sign up or log in

Post as a guest.

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy .

Not the answer you're looking for? Browse other questions tagged python if-statement assign or ask your own question .

  • The Overflow Blog
  • The world’s largest open-source business has plans for enhancing LLMs
  • Featured on Meta
  • User activation: Learnings and opportunities
  • Site maintenance - Mon, Sept 16 2024, 21:00 UTC to Tue, Sept 17 2024, 2:00...
  • What does a new user need in a homepage experience on Stack Overflow?
  • Announcing the new Staging Ground Reviewer Stats Widget

Hot Network Questions

  • Can I install a screw all the way through these threaded fork crown holes?
  • how does the US justice system combat rights violations that happen when bad practices are given a new name to avoid old rulings?
  • Is it ok for a plugin to extend a class in some other module without declaring the other module as a dependency?
  • Can All Truths Be Scientifically Verified?
  • Python script to renumber slide ids inside a pptx presentation
  • Recover lost disk space (> 270 GB)
  • Are these colored sets closed under multiplication?
  • I am an imaginary variance
  • Can the concept of a perfectly good God creating beings vulnerable to sin be philosophically justified?
  • Enumerate in Beamer
  • Browse a web page through SSH? (Need to access router web interface remotely, but only have SSH access to a different device on LAN)
  • Approach to Fermat's Last Theorem using group theory
  • Why is the Liar a problem?
  • What's the strongest material known to humanity that we could use to make Powered Armor Plates?
  • Copyright on song first performed in public
  • Seeking a Text-Based Version of Paul Dirac's 1926 Paper on Quantum Mechanics
  • How would you address the premises of Schellenberg's non-resistant divine hiddenness argument?
  • Inverses of Morphisms Necessarily Being Morphisms
  • How was Adam given the 7 Noahide laws without animals or women in existence?
  • AES-256 file encryption in c#
  • Place with signs in Chinese & Arabic
  • What makes amplifiers so expensive?
  • A word like "science/scientific" that can be used for ALL academic fields?
  • Finding out if a series converges without solving linear recurrence relation

python assignment conditional

IMAGES

  1. assignment in conditional expression python

    python assignment conditional

  2. Python If Else: Simplifying Conditional Statements

    python assignment conditional

  3. 8.9. Chained conditionals

    python assignment conditional

  4. SOLUTION: Python lesson

    python assignment conditional

  5. Python Conditional Statements: IF…Else, ELIF & Switch Case

    python assignment conditional

  6. Introduction into Python Statements: Assignment, Conditional Examples

    python assignment conditional

VIDEO

  1. Day 14 Conditional statements in python programming

  2. Week 12 :Lesson 3

  3. Python Basics: CONDITIONAL STATEMENTS (if/else) in Under a Minute! 🎲

  4. Operators & Conditional Statements

  5. Intro to Python

  6. Python FullStack Tutorial

COMMENTS

  1. Best way to do conditional assignment in python

    For more conditional code: a = b if b else val For your code: a = get_something() if get_something() else val With that you can do complex conditions like this: ... Python conditional assignment operator. Related. 5. Python: avoiding if condition? 5. pythonic way to rewrite an assignment in an if statement. 3.

  2. Python Conditional Assignment (in 3 Ways)

    Python Conditional Assignment. When you want to assign a value to a variable based on some condition, like if the condition is true then assign a value to the variable, else assign some other value to the variable, then you can use the conditional assignment operator. ... Let's see how we can do it using conditional assignment. my_list ...

  3. Conditional Statements in Python

    Python supports one additional decision-making entity called a conditional expression. (It is also referred to as a conditional operator or ternary operator in various places in the Python documentation.) Conditional expressions were proposed for addition to the language in PEP 308 and green-lighted by Guido in 2005.

  4. One line if statement in Python (ternary conditional operator)

    Many programming languages have a ternary operator, which defines a conditional expression. The most common usage is to make a terse, simple dependent assignment statement. In other words, it offers a one-line code to evaluate the first expression if the condition is true; otherwise, it considers the second expression.

  5. Python's Assignment Operator: Write Robust Assignments

    Python's assignment operators allow you to define assignment statements. This type of statement lets you create, initialize, and update variables throughout your code. Variables are a fundamental cornerstone in every piece of code, and assignment statements give you complete control over variable creation and mutation.

  6. Ternary Operator in Python

    The ternary operator in Python is a one-liner conditional expression that assigns a value based on a condition. It is written as value_if_true if condition else value_if_false. a = 5 ... A ternary is a concise way to perform a conditional assignment in a single line. In the context of programming, it typically refers to a ternary operator ...

  7. Python Ternary: How to Use It and Why It's Useful (with Examples)

    If the standard syntax for the Python ternary operator is a if condition else b, here we would re-write it as (b, a)[condition], like this: t = 90 ('Water is not boiling', 'Water is boiling')[t >= 100] 'Water is not boiling'. In the syntax above, the first item of the tuple is the value that will be returned if the condition evaluates to False ...

  8. Python One Line Conditional Assignment

    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.

  9. Conditional expression (ternary operator) in Python

    Basics of the conditional expression (ternary operator) In Python, the conditional expression is written as follows. The condition is evaluated first. If condition is True, X is evaluated and its value is returned, and if condition is False, Y is evaluated and its value is returned. If you want to switch the value based on a condition, simply ...

  10. Inline If in Python: The Ternary Operator in Python

    Let's see how we can easily turn this into an inline if statement in Python: x = 3. y = 10 if x == 1 else (20 if x == 20 else 30) print (y) # Returns 10. This is a bit different than what we've seen so far, so let's break it down a bit: First, we evaluate is x == 1. If that's true, the conditions end and y = 10.

  11. Conditional Statements in Python

    What are Conditional Statements in Python? Conditional statements in Python are used to execute a specific block of code based on the truth value of a condition. ... a statement is a logical command that a Python interpreter can read and carry out. It might be an assignment statement or an expression in Python. Multi-line Statement in Python ...

  12. How to Write the Python if Statement in one Line

    To overcome this, there is a trick many Python developers often overlook: write an if statement in a single line! Though not the standard, Python does allow us to write an if statement and its associated action in the same line. Here's the basic structure: if <expression>: <perform_action></perform_action></expression>.

  13. Introduction into Python Statements: Assignment, Conditional Examples

    Expression statements in Python are lines of code that evaluate and produce a value. They are used to assign values to variables, call functions, and perform other operations that produce a result. x = 5. y = x + 3. print(y) In this example, we assign the value 5 to the variable x, then add 3 to x and assign the result (8) to the variable y.

  14. 6. Expressions

    Assignment expressions must be surrounded by parentheses when used as expression statements and when used as sub-expressions in slicing, conditional, lambda, keyword-argument, and comprehension-if expressions and in assert, with, and assignment statements.

  15. The Walrus Operator: Python's Assignment Expressions

    Each new version of Python adds new features to the language. Back when Python 3.8 was released, the biggest change was the addition of assignment expressions.Specifically, the := operator gave you a new syntax for assigning variables in the middle of expressions. This operator is colloquially known as the walrus operator.. This tutorial is an in-depth introduction to the walrus operator.

  16. python

    PEP 572 seeks to add assignment expressions (or "inline assignments") to the language, but it has seen a prolonged discussion over multiple huge threads on the python-dev mailing list—even after multiple rounds on python-ideas. Those threads were often contentious and were clearly voluminous to the point where many probably just tuned them out.

  17. Assignment Expressions: The Walrus Operator

    In this lesson, you'll learn about the biggest change in Python 3.8: the introduction of assignment expressions.Assignment expression are written with a new notation (:=).This operator is often called the walrus operator as it resembles the eyes and tusks of a walrus on its side.. Assignment expressions allow you to assign and return a value in the same expression.

  18. Operators and Expressions in Python

    When you make an assignment like y = x, Python creates a second reference to the same object. Again, you can confirm that with the id() function or the is operator: Python ... In this example, you use a conditional statement to check whether the input string has fewer than 8 characters. The assignment expression, (n := len ...

  19. Conditionals Practice :: Introduction to Python

    Recall that you can use Boolean comparators such as < and > to compare two strings in Python. Also, pay special attention to the capitalization of the words "First" and "last" in the description above. Your program should include at least two conditional statements.

  20. Assign within if statement Python

    Python conditional variable assignment. 2. Python - assign value and check condition in IF statment. 0. python assignment fails in else part of conditional operation. 0. Assigning variable values to if statement. 0. Python assignment, Compound if statment. 0. Assign a new value within if function.