Movatterモバイル変換


[0]ホーム

URL:


— FREE Email Series —

🐍 Python Tricks 💌

Python Tricks Dictionary Merge

🔒 No spam. Unsubscribe any time.

Browse TopicsGuided Learning Paths
Basics Intermediate Advanced
apibest-practicescareercommunitydatabasesdata-sciencedata-structuresdata-vizdevopsdjangodockereditorsflaskfront-endgamedevguimachine-learningnumpyprojectspythontestingtoolsweb-devweb-scraping

Table of Contents

Operators and Expressions in Python

Operators and Expressions in Python

byLeodanis Pozo Ramos Jan 11, 2025basicspython

Table of Contents

Remove ads

Python operators enable you to perform computations by combining objects and operators into expressions. Understanding Python operators is essential for manipulating data effectively.

This tutorial covers arithmetic, comparison, Boolean, identity, membership, bitwise, concatenation, and repetition operators, along with augmented assignment operators. You’ll also learn how to build expressions using these operators and explore operator precedence to understand the order of operations in complex expressions.

By the end of this tutorial, you’ll understand that:

  • Arithmetic operators perform mathematical calculations on numeric values.
  • Comparison operators evaluate relationships between values, returningBoolean results.
  • Boolean operators create compound logical expressions.
  • Identity operators determine if two operands refer to the same object.
  • Membership operators check for the presence of a value in a container.
  • Bitwise operators manipulate data at the binary level.
  • Concatenation and repetition operators manipulate sequence data types.
  • Augmented assignment operators simplify expressions involving the same variable.

This tutorial provides a comprehensive guide to Python operators, empowering you to create efficient and effective expressions in your code. To get the most out of this tutorial, you should have a basic understanding of Python programming concepts, such asvariables,assignments, and built-indata 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:


Operators and Expressions in Python

Interactive Quiz

Python Operators and Expressions

Test your understanding of Python operators and expressions.

Getting Started With Operators and Expressions

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

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:

Python
>>>-273.15-273.15>>>5-23

In this code snippet, the minus sign (-) in the first example is a unary operator, and the number273.15 is the operand. In the second example, the same symbol is a binary operator, and the numbers5 and2 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, runBoolean tests, assign values to variables, and more. In Python, an operator may be a symbol, a combination of symbols, or akeyword, 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:

Python
>>>42==42True

In this example, you use the Python equality operator (==) to compare two numbers. As a result, you getTrue, 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 aboutBoolean operators and expressions. So, instead of the odd signs like||,&&, and! that many other programming languages use, Python usesor,and, andnot.

Using keywords instead of odd signs is a really cool design decision that’s consistent with the fact that Python loves and encouragescode’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 andrepetition 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 anexpression. Operators by themselves don’t do much:

Python
>>>-  File"<input>", line1-^SyntaxError:incomplete input>>>==  File"<input>", line1==^^SyntaxError:incomplete input>>>or  File"<input>", line1or^^SyntaxError:incomplete input

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

So, what is an expression anyway? Python hassimple andcompound statements. A simple statement is a construct that occupies a singlelogical line, like an assignment statement. A compound statement is a construct that occupies multiple logical lines, such as afor loop or aconditional statement. Anexpression is a simple statement that produces and returns a value.

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

Python
>>>7+512>>>42/221.0>>>5==5True

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 barefunction call is an expression that doesn’t require any operator:

Python
>>>abs(-7)7>>>pow(2,8)256>>>print("Hello, World!")Hello, World!

In the first example, you call the built-inabs() function to get theabsolute value of-7. Then, you compute2 to the power of8 using the built-inpow() function. These function calls occupy a single logical line and return a value. So, they’re expressions.

Finally, the call to the built-inprint() function is another expression. This time, the function doesn’treturn a fruitful value, but it still returnsNone, which is the Pythonnull type. So, the call is technically an expression.

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

Even though all expressions are statements, not all statements are expressions. For example, pureassignment 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 sectionThe 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 and Statements

Theassignment 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 avariable, 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 toassign 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 outPython’s Assignment Operator: Write Robust Assignments.

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

Python
>>>number=42>>>day="Friday">>>digits=(0,1,2,3,4,5,6,7,8,9)>>>letters=["a","b","c"]

In the first statement, you create thenumber variable, which holds a reference to thenumber42 in your computer’s memory. You can also say that the namenumberpoints to42, which is a concrete object.

In the rest of the examples, you create other variables that point to other types of objects, such as astring,tuple, andlist, 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 and Expressions in Python

Arithmetic operators are those operators that allow you to performarithmetic 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:

OperatorTypeOperationSample ExpressionResult
+UnaryPositive+aa without any transformation since this is simply a complement to negation
+BinaryAdditiona + bThe arithmetic sum ofa andb
-UnaryNegation-aThe value ofa but with the opposite sign
-BinarySubtractiona - bb subtracted froma
*BinaryMultiplicationa * bThe product ofa andb
/BinaryDivisiona / bThe quotient ofa divided byb, expressed as a float
%BinaryModuloa % bThe remainder ofa divided byb
//BinaryFloor division or integer divisiona // bThe quotient ofa divided byb, rounded to the next smallest whole number
**BinaryExponentiationa**ba raised to the power ofb

Note thata andb in theSample Expression column represent numeric values, such asinteger,floating-point,complex,rational, anddecimal numbers.

Here are some examples of these operators in use:

Python
>>>a=5>>>b=2>>>+a5>>>-b-2>>>a+b7>>>a-b3>>>a*b10>>>a/b2.5>>>a%b1>>>a//b2>>>a**b25

In this code snippet, you first create two new variables,a andb, holding5 and2, respectively. Then you use these variables to create different arithmetic expressions using a specific operator in each expression.

Note: The PythonREPL 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 theprint() function to check the result of an expression. You can just type in the expression and pressEnter 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:

Python
>>>10/52.0>>>10.0/52.0

In the first example,10 is evenly divisible by5. Therefore, this operation could return the integer2. However, it returns the floating-point number2.0. In the second example,10.0 is a floating-point number, and5 is an integer. In this case, Python internally promotes5 to5.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:

Python
>>>10/5j-2j

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:

Python
>>>10//42>>>-10//-42>>>10//-4-3>>>-10//4-3

Floor division alwaysrounds 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 Pythoncomparison operators allow you tocompare numerical values and any other objects that support them. The table below lists all the currently available comparison operators in Python:

OperatorOperationSample ExpressionResult
==Equal toa == bTrue if the value ofa is equal to the value ofb
False otherwise
!=Not equal toa != bTrue ifa isn’t equal tob
False otherwise
<Less thana < bTrue ifa is less thanb
False otherwise
<=Less than or equal toa <= bTrue ifa is less than or equal tob
False otherwise
>Greater thana > bTrue ifa is greater thanb
False otherwise
>=Greater than or equal toa >= bTrue ifa is greater than or equal tob
False otherwise

The comparison operators are all binary. This means that they require left and right operands. These operators always return a Boolean value (True orFalse) that depends on thetruth 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 getFalse as a result:

Python
>>>2=="2"False

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

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

Python
>>>5<"7"Traceback (most recent call last):...TypeError:'<' not supported between instances of 'int' and 'str'

In this example, Python raises aTypeError 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 likeconditional statements andwhile loops. They allow you to make decisions and define a program’scontrol 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.

Comparison of Integer Values

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 callednatural 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:

Python
>>>a=10>>>b=20>>>a==bFalse>>>a!=bTrue>>>a<bTrue>>>a<=bTrue>>>a>bFalse>>>a>=bFalse>>>x=30>>>y=30>>>x==yTrue>>>x!=yFalse>>>x<yFalse>>>x<=yTrue>>>x>yFalse>>>x>=yTrue

In the first set of examples, you define two variables,a andb, to run a few comparisons between them. The value ofa is less than the value ofb. 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.

Comparison of Floating-Point Values

Comparing floating-point numbers is a bitmore complicated than comparing integers. The value stored in afloat 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:

Python
>>>x=1.1+2.2>>>x==3.3False>>>1.1+2.23.3000000000000003

Yikes! The internal representation of this addition isn’t exactly equal to3.3, as you can see in the final example. So, comparingx to3.3 with the equality operator returnsFalse.

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.

Themath module from the standard library provides a function conveniently calledisclose() that will help you withfloat comparison. The function takes two numbers and tests them for approximate equality:

Python
>>>frommathimportisclose>>>x=1.1+2.2>>>isclose(x,3.3)True

In this example, you use theisclose() function to comparex and3.3 for approximate equality. This time, you getTrue as a result because both numbers are close enough to be considered equal.

For further details on usingisclose(), check out theFind the Closeness of Numbers With Pythonisclose() section inThe Pythonmath Module: Everything You Need to Know.

Comparison of Strings

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’sUnicodecode point. Unicode is Python’sdefault character set.

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

Python
>>>ord("A")65>>>ord("a")97>>>"A"=="a"False>>>"A">"a"False>>>"A"<"a"True

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 useslexicographical 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:

Python
>>>"Hello">"HellO"True>>>ord("o")111>>>ord("O")79

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:

Python
>>>"Hello">"Hello, World!"False

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.

Comparison of Lists and Tuples

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:

Python
>>>[2,3]==[2,3]True>>>(2,3)==(2,3)True>>>[5,6,7]<[7,5,6]True>>>(5,6,7)<(7,5,6)True>>>[4,3,2]<[4,3,2]False>>>(4,3,2)<(4,3,2)False

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 the2 in the left operand and the2 in the right operand. Because they’re equal, Python continues comparing3 and3 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, youcan’t compare lists and tuples using the<,>,<=, and>= operators:

Python
>>>[2,3]==(2,3)False>>>[2,3]!=(2,3)True>>>[2,3]>(2,3)Traceback (most recent call last):...TypeError:'>' not supported between instances of 'list' and 'tuple'>>>[2,3]<=(2,3)Traceback (most recent call last):...TypeError:'<=' not supported between instances of 'list' and 'tuple'

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 aTypeError telling you that the operation isn’t supported.

You can also compare lists and tuples of different lengths:

Python
>>>[5,6,7]<[8]True>>>(5,6,7)<(8,)True>>>[5,6,7]==[5]False>>>(5,6,7)==(5,)False>>>[5,6,7]>[5]True>>>(5,6,7)>(5,)True

In the first two examples, you getTrue as a result because5 is less than8. That fact is sufficient for Python to solve the comparison. In the second pair of examples, you getFalse. 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 compares5 with5. 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, andnot. They define a set of operations denoted by the generic operatorsAND,OR, andNOT. 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.

Boolean Expressions Involving Boolean Operands

You’ll find many objects and expressions that are of Boolean type orbool, as Python calls this type. In other words, many objects evaluate toTrue orFalse, which are the Python Boolean values.

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

Python
>>>age=20>>>is_adult=age>18>>>is_adultTrue>>>type(is_adult)<class 'bool'>

In this example, the expressionage > 18 returns a Boolean value, which you store in theis_adult variable. Nowis_adult is ofbool type, as you can see after calling the built-intype() function.

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

Consider the following examples:

Python
>>>number=42>>>validation_conditions=(...isinstance(number,int),...number%2==0,...)>>>all(validation_conditions)True>>>callable(number)False>>>callable(print)True

In this code snippet, you first define a variable callednumber using your old friend the assignment operator. Then you create another variable calledvalidation_conditions. This variable holds a tuple of expressions. The first expression usesisinstance() to check whethernumber 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 dividingnumber by2, and the equality operator compares the result with0, returningTrue orFalse as the comparison’s result.

Then you use theall() function to determine if all the conditions are true. In this example, becausenumber = 42, the conditions are true, andall() returnsTrue. You can play with the value ofnumber if you’d like to experiment a bit.

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

Thenumber variable isn’t callable, and the function returnsFalse, accordingly. In contrast, theprint() function is callable, socallable() returnsTrue.

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

Logical expressions involvingand,or, andnot are straightforward when the operands are Boolean. Here’s a summary. Note thatx andy represent Boolean operands:

OperatorSample ExpressionResult
andx and yTrue if bothx andy areTrue
False otherwise
orx or yTrue if eitherx ory isTrue
False otherwise
notnot xTrue ifx isFalse
False ifx isTrue

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. Unlikeand andor, which are binary operators, thenot 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 theand operator with Boolean operands:

Python
>>>5<7and3==3True>>>5<7and3!=3False>>>5>7and3==3False>>>5>7and3!=3False

In the first example, both operands returnTrue. Therefore, theand expression returnsTrue as a result. In the second example, the left-hand operand isTrue, but the right-hand operand isFalse. Because of this, theand operator returnsFalse.

In the third example, the left-hand operand isFalse. In this case, theand operator immediately returnsFalse and never evaluates the3 == 3 condition. This behavior is calledshort-circuit evaluation. You’ll learn more about it in a moment.

Note: Short-circuit evaluation is also calledMcCarthy evaluation in honor of computer scientistJohn McCarthy.

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

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

Python
>>>5<7or3==3True>>>5<7or3!=3True>>>5>7or3==3True>>>5>7or3!=3False

In the first three examples, at least one of the conditions returnsTrue. In all cases, theor operator returnsTrue. Note that if the left-hand operand isTrue, thenor applies short-circuit evaluation and doesn’t evaluate the right-hand operand. This makes sense. If the left-hand operand isTrue, thenor 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 areFalse, and this is the only situation whereor returnsFalse. It’s important to note that if the left-hand operand isFalse, thenor has to evaluate the right-hand operand to arrive at a final conclusion.

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

Python
>>>5<7True>>>not5<7False

If you placenot before an expression, then you get the inverse truth value. When the expression returnsTrue, you getFalse. When the expression evaluates toFalse, you getTrue.

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

Evaluation of Regular Objects in a Boolean Context

In practice, most Python objects and expressions aren’t Boolean. In other words, most objects and expressions don’t have aTrue orFalse value but a different type of value. However, you can use any Python object in a Boolean context, such as a conditional statement or awhile 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 returnsFalse 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 andFalse.
  • 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-inbool() function with that object as an argument. Ifbool() returnsTrue, then the object istruthy. Ifbool() returnsFalse, then it’sfalsy.

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

Python
>>>bool(0),bool(0.0),bool(0.0+0j)(False, False, False)>>>bool(-3),bool(3.14159),bool(1.0+1j)(True, True, True)

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 thebuilt-in functions page. This is one of those cases wherepracticality beats purity.

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

Python
>>>bool("")False>>>bool(" ")True>>>bool("Hello")True

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, anddictionaries, are falsy when they’re empty. Otherwise, Python considers them truthy objects:

Python
>>>bool([])False>>>bool([1,2,3])True>>>bool(())False>>>bool(("John",25,"Python Dev"))True>>>bool(set())False>>>bool({"square","circle","triangle"})True>>>bool({})False>>>bool({"name":"John","age":25,"job":"Python Dev"})True

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

In general, if.__len__() returns0, 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.

Boolean Expressions Involving Other Types of Operands

You can also use any objects, such as numbers or strings, as operands toand,or, andnot. 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 thatcombine 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 andy, in anand expression:

Ifx isx and y returns
Truthyy
Falsyx

It’s important to emphasize a subtle detail in the above table. When you useand in an expression, you don’t always getTrue orFalse as a result. Instead, you get one of the operands. You only getTrue orFalse 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:

Python
>>>3and44>>>0and40>>>3and00

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 because0 is falsy, so Python returns0 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 theand operator, check outUsing the “and” Boolean Operator in Python.

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

Ifx isx or y returns
Truthyx
Falsyy

Again, the expressionx or y doesn’t evaluate to eitherTrue orFalse. Instead, it returns one of its operands,x ory.

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:

Python
>>>3or43>>>0or44>>>3or03

In the first example, the left-hand operand is truthy, andor 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 likex or y is truthy if eitherx ory is truthy, and falsy if bothx andy 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:

Python
>>>0or[][]

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

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

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

Ifx isnot x returns
TruthyFalse
FalsyTrue

Thenot operator has a uniform behavior. It always returns a Boolean value. This behavior differs from its sibling operators,and andor.

Here are some code examples:

Python
>>>not3False>>>not0True

In the first example, the operand,3, is truthy from Python’s point of view. So, the operator returnsFalse. In the second example, the operand is falsy, andnot returnsTrue.

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

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

Compound Logical Expressions and Short-Circuit Evaluation

So far, you’ve seen expressions with only a singleor orand 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 usingor, consider the following toy example:

Python
x1orx2orx3or...orxn

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

Note: In an expression like the one above, Python usesshort-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 thex that terminates the evaluation.

To help demonstrate short-circuit evaluation, suppose that you have anidentity 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:

Python
>>>deff(arg):...print(f"-> f({arg}) ={arg}")...returnarg...>>>f(0)-> f(0) = 00>>>f(False)-> f(False) = FalseFalse>>>f(1.5)-> f(1.5) = 1.51.5

Thef() 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 expressionf(arg) be truthy or falsy by specifying a value forarg that’s truthy or falsy, respectively.

Now, consider the following compound logical expression:

Python
>>>f(0)orf(False)orf(1)orf(2)orf(3)-> f(0) = 0-> f(False) = False-> f(1) = 11

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

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

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

Python
x1andx2andx3and...andxn

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:

Python
>>>f(1)andf(False)andf(2)andf(3)-> f(1) = 1-> f(False) = FalseFalse>>>f(1)andf(0.0)andf(2)andf(3)-> f(1) = 1-> f(0.0) = 0.00.0

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 thef(2) nor thef(3) call occurs. In the end, the expressions returnFalse and0.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:

Python
>>>f(1)andf(2.2)andf("Hello")-> f(1) = 1-> f(2.2) = 2.2-> f(Hello) = Hello'Hello'>>>f(1)andf(2.2)andf(0)-> f(1) = 1-> f(2.2) = 2.2-> f(0) = 00

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.

Idioms That Exploit Short-Circuit Evaluation

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 andb, and you want to know whether the division ofb bya results in a number greater than0. In this case, you can run the following expression or condition:

Python
>>>a=3>>>b=1>>>(b/a)>0True

This code works. However, you need to account for the possibility thata might be0, in which case you’ll get anexception:

Python
>>>a=0>>>b=1>>>(b/a)>0Traceback (most recent call last):...ZeroDivisionError:division by zero

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

Python
>>>a=0>>>b=1>>>a!=0and(b/a)>0False

Whena is0,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:

Python
defis_divisible(a,b):returnb!=0anda%b==0

In this function, ifb is0, thena / b isn’t defined. So, the numbers aren’t divisible. Ifb is different from0, 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 theor operator:

Python
>>>country="Canada">>>default_country="United States">>>countryordefault_country'Canada'>>>country="">>>countryordefault_country'United States'

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

On the other hand, ifcountry is an emptystring, 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 useor like in the following snippet:

Python
data_is_cleanorclean_data(data)

In this construct, yourclean_data() function represents a costly operation. Because of short-circuit evaluation, this function will only run whendata_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 theand operator:

Python
data_is_updatedandprocess_data(data)

In this example, theand operator evaluatesdata_is_updated. If this variable is true, then the evaluation continues, and theprocess_data() function runs. Otherwise, the evaluation stops, andprocess_data() never runs.

Compound vs Chained Expressions

Sometimes you have a compound expression that uses theand 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:

Python
>>>number=5>>>number>=0andnumber<=10True>>>number=42>>>number>=0andnumber<=10False

In this example, you use theand operator to join two comparison expressions that allow you to find out ifnumber is in the interval from0 to10, 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:

Python
>>>number=5>>>0<=number<=10True

This expression is more concise and readable than the original expression. You can quickly realize that this code is checking if the number is between0 and10. 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 evaluating0 <= number, which is true. This true value would then be compared with10, which doesn’t make much sense, so the expression fails.

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

Conditional Expressions or the Ternary Operator

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

However, in Python, the expression looks more readable:

Python
variable=expression_1ifconditionelseexpression_2

This expression returnsexpression_1 if the condition is true andexpression_2 otherwise. Note that this expression is equivalent to a regular conditional like the following:

Python
ifcondition:variable=expression_1else:variable=expression_2

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 theand andor operators in an expression like the following:

Python
variable=conditionandexpression_1orexpression_2

However, this expression doesn’t work as expected, returningexpression_2 whenexpression_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:

Python
>>>day="Sunday">>>open_time="11AM"ifday=="Sunday"else"9AM">>>open_time'11AM'>>>day="Monday">>>open_time="11AM"ifday=="Sunday"else"9AM">>>open_time'9AM'

Whenday 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 theand andor operators, the conditional expression returns the value of one of its expressions rather than a Boolean value.

Identity Operators and Expressions in Python

Python provides two operators,is andis not, that allow you to determine whether two operands have the sameidentity. 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 outPython ‘!=’ Is Not ‘is not’: Comparing Objects in Python.

Here’s a summary of Python’s identity operators. Note thatx andy are variables that point to objects:

OperatorSample ExpressionResult
isx is yTrue ifx andy hold a reference to the same in-memory object
False otherwise
is notx is not yTrue ifx points to an object different from the object thaty points to
False 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 andy, that refer to objects that are equal but not identical:

Python
>>>x=1001>>>y=1001>>>x==yTrue>>>xisyFalse

In this example,x andy refer to objects whose value is1001. So, they’re equal. However, they don’t reference the same object. That’s why theis operator returnsFalse. You can check an object’s identity using the built-inid() function:

Python
>>>id(x)4417772080>>>id(y)4417766416

As you can conclude from theid() output,x andy don’t have the same identity. So, they’re different objects, and because of that, the expressionx is y returnsFalse. In other words, you getFalse because you have two different instances of1001 stored in your computer’s memory.

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

Python
>>>a="Hello, Pythonista!">>>b=a>>>id(a)4417651936>>>id(b)4417651936>>>aisbTrue

In this example,a andb hold references to the same object, the string"Hello, Pythonista!". Therefore, theid() function returns the same identity when you call it witha andb. Similarly, theis operator returnsTrue.

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

Finally, theis not operator is the opposite ofis. So, you can useis not to determine if two namesdon’t refer to the same object:

Python
>>>x=1001>>>y=1001>>>xisnotyTrue>>>a="Hello, Pythonista!">>>b=a>>>aisnotbFalse

In the first example, becausex andy point to different objects in your computer’s memory, theis not operator returnsTrue. In the second example, becausea andb are references to the same object, theis not operator returnsFalse.

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

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

Membership Operators and Expressions in Python

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 valueis oris not amember of a collection of values. Python calls this kind of check amembership test.

Note: For a deep dive into how Python’s membership tests work, check outPython’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 themembership operators in Python:

OperatorSample ExpressionResult
invalue in collectionTrue ifvalueis present incollection
False otherwise
not invalue not in collectionTrue ifvalueis not present incollection of values
False otherwise

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

Note: The syntaxnot 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 usevalue not in collection, which almost reads as plain English.

The Pythonin andnot 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 thein operator, below you have two demonstrative examples consisting of determining whether a value is in a list:

Python
>>>5in[2,3,5,9,7]True>>>8in[2,3,5,9,7]False

The first expression returnsTrue because5 is in the list of numbers. The second expression returnsFalse because8 isn’t in the list.

Thenot in membership operator runs the opposite test as thein operator. It allows you to check whether an integer valueis not in a collection of values:

Python
>>>5notin[2,3,5,9,7]False>>>8notin[2,3,5,9,7]True

In the first example, you getFalse because5 is in the target list. In the second example, you getTrue because8 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 valueis not part of a given collection of values.

Concatenation and Repetition Operators and Expressions

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 aconcatenation operator, and the* operator represents therepetition operator:

OperatorOperationSample ExpressionResult
+Concatenationseq_1 + seq_2A new sequence containing all the items from both operands
*Repetitionseq * nA new sequence containing the items ofseq repeatedn 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 outEfficient String Concatenation in Python.

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

Python
>>>"Hello, "+"World!"'Hello, World!'>>>("A","B","C")+("D","E","F")('A', 'B', 'C', 'D', 'E', 'F')>>>[0,1,2,3]+[4,5,6][0, 1, 2, 3, 4, 5, 6]

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 theConcatenating Lists section in the tutorialPython’slist 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:

Python
>>>"Hello"*3'HelloHelloHello'>>>3*"World!"'World!World!World!'>>>("A","B","C")*3('A', 'B', 'C', 'A', 'B', 'C', 'A', 'B', 'C')>>>3*[1,2,3][1, 2, 3, 1, 2, 3, 1, 2, 3]

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.

The Walrus Operator and Assignment Expressions

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.

SincePython 3.8, you have access to a new operator that allows for a new type of assignment. This new assignment is calledassignment expression ornamed expression. The new operator is called thewalrus operator, and it’s the combination of a colon and an equal sign (:=).

Note: The namewalrus 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 outThe Walrus Operator: Python’s Assignment Expressions.

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

  1. Returns the expression’s result
  2. 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:

Python
(variable:=expression)

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:

Python
>>>defvalidate_length(string):...if(n:=len(string))<8:...print(f"Length{n} is too short, needs at least 8")...else:...print(f"Length{n} is okay!")...>>>validate_length("Pythonista")Length 10 is okay!>>>validate_length("Python")Length 6 is too short, needs at least 8

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

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

Bitwise Operators and Expressions in Python

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

OperatorOperationSample ExpressionResult
&Bitwise ANDa & b• Each bit position in the result is the logical AND of the bits in the corresponding position of the operands.
1 if both bits are1, otherwise0.
|Bitwise ORa | b• Each bit position in the result is the logicalOR of the bits in the corresponding position of the operands.
1 if either bit is1, otherwise0.
~Bitwise NOT~a• Each bit position in the result is the logical negation of the bit in the corresponding position of the operand.
1 if the bit is0 and0 if the bit is1.
^Bitwise XOR (exclusive OR)a ^ b• Each bit position in the result is the logicalXOR of the bits in the corresponding position of the operands.
1 if the bits in the operands are different,0 if they’re equal.
>>Bitwise right shifta >> nEach bit is shifted rightn places.
<<Bitwise left shifta << nEach bit is shifted leftn 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 outBitwise Operators in Python. You can also check outBuild 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:

Python
>>># Bitwise AND>>>#   0b1100    12>>># & 0b1010    10>>># -------->>># = 0b1000     8>>>bin(0b1100&0b1010)'0b1000'>>>12&108>>># Bitwise OR>>>#   0b1100    12>>># | 0b1010    10>>># -------->>># = 0b1110    14>>>bin(0b1100|0b1010)'0b1110'>>>12|1014

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-inbin() function to display the result as a binary object. If you don’t wrap the expression in a call tobin(), then you’ll get the integer representation of the output.

Operator Precedence in Python

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:

Python
>>>20+4*1060

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

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

All operators that Python supports have aprecedence 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:

OperatorsDescription
**Exponentiation
+x,-x,~xUnary positive, unary negation, bitwise negation
*,/,//,%Multiplication, division, floor division,modulo
+,-Addition, subtraction
<<,>>Bitwise shifts
&Bitwise AND
^Bitwise XOR
|Bitwise OR
==,!=,<,<=,>,>=,is,is not,in,not inComparisons, identity, and membership
notBoolean NOT
andBoolean AND
orBoolean 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:

Python
>>>2*3**4*5810

In the example above, Python first raises3 to the power of4, which equals81. Then, it carries out the multiplications in order from left to right:2 * 81 = 162 and162 * 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:

Python
>>>(20+4)*10240>>>2*3**(4*5)6973568802

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

In the second example, Python evaluates4 * 5 first. Then it raises3 to the power of the resulting value. Finally, Python multiplies the result by2, returning6973568802.

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:

Python
(a<10)and(b>30)

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

Python
a<10andb>30

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.

Augmented Assignment Operators and Expressions

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:

Python
>>>total=10>>>total=total+5>>>total15

In this example,total is anaccumulator variable that you use toaccumulate successive values. You should read this example astotal is equal to the current value oftotal plus5. This expression effectively increases the value oftotal, which is now15.

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:

Python
>>>count=count+1Traceback (most recent call last):...NameError:name 'count' is not defined. Did you mean: 'round'?

In this example, thecount variable isn’t defined before the assignment, so it doesn’t have a current value. In consequence, Python raises aNameError 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 calledaugmented assignment:

Python
>>>total=10>>>total+=5>>>total15

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

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

Python
variable$=expression

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:

  1. Evaluateexpression to produce a value.
  2. Run the operation defined by the operator that prefixes the assignment operator (=), using the current value ofvariable and the return value ofexpression as operands.
  3. Assign the resulting value back tovariable.

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

OperatorDescriptionSample ExpressionEquivalent Expression
+=Adds the right operand to the left operand and stores the result in the left operandx += yx = x + y
-=Subtracts the right operand from the left operand and stores the result in the left operandx -= yx = x - y
*=Multiplies the right operand with the left operand and stores the result in the left operandx *= yx = x * y
/=Divides the left operand by the right operand and stores the result in the left operandx /= yx = x / y
//=Performsfloor division of the left operand by the right operand and stores the result in the left operandx //= yx = x // y
%=Finds the remainder of dividing the left operand by the right operand and stores the result in the left operandx %= yx = x % y
**=Raises the left operand to the power of the right operand and stores the result in the left operandx **= yx = x**y

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:

OperatorOperationExampleEquivalent
&=Augmented bitwise AND (conjunction)x &= yx = x & y
|=Augmented bitwise OR (disjunction)x |= yx = x | y
^=Augmented bitwise XOR (exclusive disjunction)x ^= yx = x ^ y
>>=Augmented bitwise right shiftx >>= yx = x >> y
<<=Augmented bitwise left shiftx <<= yx = x << y

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

OperatorDescriptionExample
+=• 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.
seq_1 += seq_2
*=• Addsseq to itselfn 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.
seq *= n

Note that the augmentedconcatenation operator works on two sequences, while the augmentedrepetition operator works on a sequence and an integer number.

Conclusion

Now you know whatoperators 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 ofexpressions and perform computations in your code.

In this tutorial, you’ve learned:

  • What Python’sarithmetic operators are and how to use them inarithmetic expressions
  • What Python’scomparison,Boolean,identity,membership operators are
  • How to writeexpressions using comparison, Boolean, identity, and membership operators
  • Whichbitwise operators Python supports and how to use them
  • How to combine and repeat sequences using theconcatenation andrepetition operators
  • What theaugmented 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:

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

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.

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:


Operators and Expressions in Python

Interactive Quiz

Python Operators and Expressions

Test your understanding of Python operators and expressions.

Frequently Asked Questions

Now that you have some experience with Python operators, you can use the questions and answers below to check your understanding and recap what you’ve learned.

These FAQs are related to the most important concepts you’ve covered in this tutorial. Click theShow/Hide toggle beside each question to reveal the answer.

Python has more than seven operators, but there are sevenarithmetic operators. These are addition (+), subtraction (-), multiplication (*), division (/), modulo (%), floor division or integer division (//), and exponentiation (**).

The+= operator in Python is an augmented assignment operator that adds the right operand to the left operand and assigns the result to the left operand.

The%= operator in Python is an augmented assignment operator that calculates the remainder of dividing the left operand by the right operand and assigns the result to the left operand.

The// operator in Python performs floor division or integer division, which divides the left operand by the right operand and rounds the result down to the nearest whole number.

The four basic arithmetic operators in Python are addition (+), subtraction (-), multiplication (*), and division (/).

🐍 Python Tricks 💌

Get a short & sweetPython 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

AboutLeodanis 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.

» More about Leodanis

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:

MasterReal-World Python Skills With Unlimited Access to Real Python

Locked learning resources

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

Level Up Your Python Skills »

MasterReal-World Python Skills
With Unlimited Access to Real Python

Locked learning resources

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

Level Up Your Python Skills »

What Do You Think?

Rate this article:

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 andget answers to common questions in our support portal.


Looking for a real-time conversation? Visit theReal Python Community Chat or join the next“Office Hours” Live Q&A Session. Happy Pythoning!

Keep Learning

Related Topics:basicspython

Related Tutorials:

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

Operators and Expressions in Python (Cheat Sheet)

🔒 No spam. We take your privacy seriously.


[8]ページ先頭

©2009-2025 Movatter.jp