Python Operators: Arithmetic, Assignment, Comparison, Logical, Identity, Membership, Bitwise

Operators are special symbols that perform some operation on operands and returns the result. For example, 5 + 6 is an expression where + is an operator that performs arithmetic add operation on numeric left operand 5 and the right side operand 6 and returns a sum of two operands as a result.

Python includes the operator module that includes underlying methods for each operator. For example, the + operator calls the operator.add(a,b) method.

Above, expression 5 + 6 is equivalent to the expression operator.add(5, 6) and operator.__add__(5, 6) . Many function names are those used for special methods, without the double underscores (dunder methods). For backward compatibility, many of these have functions with the double underscores kept.

Python includes the following categories of operators:

Arithmetic Operators

Assignment operators, comparison operators, logical operators, identity operators, membership test operators, bitwise operators.

Arithmetic operators perform the common mathematical operation on the numeric operands.

The arithmetic operators return the type of result depends on the type of operands, as below.

  • If either operand is a complex number, the result is converted to complex;
  • If either operand is a floating point number, the result is converted to floating point;
  • If both operands are integers, then the result is an integer and no conversion is needed.

The following table lists all the arithmetic operators in Python:

Operation Operator Function Example in Python Shell
Sum of two operands + operator.add(a,b)
Left operand minus right operand - operator.sub(a,b)
* operator.mul(a,b)
Left operand raised to the power of right ** operator.pow(a,b)
/ operator.truediv(a,b)
equivilant to // operator.floordiv(a,b)
Reminder of % operator.mod(a, b)

The assignment operators are used to assign values to variables. The following table lists all the arithmetic operators in Python:

Operator Function Example in Python Shell
=
+= operator.iadd(a,b)
-= operator.isub(a,b)
*= operator.imul(a,b)
/= operator.itruediv(a,b)
//= operator.ifloordiv(a,b)
%= operator.imod(a, b)
&= operator.iand(a, b)
|= operator.ior(a, b)
^= operator.ixor(a, b)
>>= operator.irshift(a, b)
<<= operator.ilshift(a, b)

The comparison operators compare two operands and return a boolean either True or False. The following table lists comparison operators in Python.

Operator Function Description Example in Python Shell
> operator.gt(a,b) True if the left operand is higher than the right one
< operator.lt(a,b) True if the left operand is lower than right one
== operator.eq(a,b) True if the operands are equal
!= operator.ne(a,b) True if the operands are not equal
>= operator.ge(a,b) True if the left operand is higher than or equal to the right one
<= operator.le(a,b) True if the left operand is lower than or equal to the right one

The logical operators are used to combine two boolean expressions. The logical operations are generally applicable to all objects, and support truth tests, identity tests, and boolean operations.

Operator Description Example
and True if both are true
or True if at least one is true
not Returns True if an expression evalutes to false and vice-versa

The identity operators check whether the two objects have the same id value e.i. both the objects point to the same memory location.

Operator Function Description Example in Python Shell
is operator.is_(a,b) True if both are true
is not operator.is_not(a,b) True if at least one is true

The membership test operators in and not in test whether the sequence has a given item or not. For the string and bytes types, x in y is True if and only if x is a substring of y .

Operator Function Description Example in Python Shell
in operator.contains(a,b) Returns True if the sequence contains the specified item else returns False.
not in not operator.contains(a,b) Returns True if the sequence does not contains the specified item, else returns False.

Bitwise operators perform operations on binary operands.

Operator Function Description Example in Python Shell
& operator.and_(a,b) Sets each bit to 1 if both bits are 1.
| operator.or_(a,b) Sets each bit to 1 if one of two bits is 1.
^ operator.xor(a,b) Sets each bit to 1 if only one of two bits is 1.
~ operator.invert(a) Inverts all the bits.
<< operator.lshift(a,b) Shift left by pushing zeros in from the right and let the leftmost bits fall off.
>> operator.rshift(a,b) Shift right by pushing copies of the leftmost bit in from the left, and let the rightmost bits fall off.
  • Compare strings in Python
  • Convert file data to list
  • Convert User Input to a Number
  • Convert String to Datetime in Python
  • How to call external commands in Python?
  • How to count the occurrences of a list item?
  • How to flatten list in Python?
  • How to merge dictionaries in Python?
  • How to pass value by reference in Python?
  • Remove duplicate items from list in Python
  • More Python articles

arithmetic assignment operator in python

We are a team of passionate developers, educators, and technology enthusiasts who, with their combined expertise and experience, create in -depth, comprehensive, and easy to understand tutorials.We focus on a blend of theoretical explanations and practical examples to encourages hands - on learning. Visit About Us page for more information.

  • Python Questions & Answers
  • Python Skill Test
  • Python Latest Articles

Python Operators Cheat Sheet

Author's photo

  • python basics
  • learn python

Discover the essential Python operators and how to effectively use them with our comprehensive cheat sheet. We cover everything from arithmetic to bitwise operations!

If you’ve ever written a few lines of Python code, you are likely familiar with Python operators. Whether you're doing basic arithmetic calculations, creating variables, or performing complex logical operations, chances are that you had to use a Python operator to perform the task. But just how many of them exist, and what do you use them for?

In this cheat sheet, we will cover every one of Python’s operators:

  • Arithmetic operators.
  • Assignment operators.
  • Comparison operators.
  • Logical operators.
  • Identity operators.
  • Membership operators.
  • Bitwise operators.

Additionally, we will discuss operator precedence and its significance in Python.

If you're just starting out with Python programming, you may want to look into our Python Basics Track . Its nearly 40 hours of content covers Python operators and much more; you’ll get an excellent foundation to build your coding future on.

Without further ado, let's dive in and learn all about Python operators.

What Are Python Operators?

Python operators are special symbols or keywords used to perform specific operations. Depending on the operator, we can perform arithmetic calculations, assign values to variables, compare two or more values, use logical decision-making in our programs, and more.

How Operators Work

Operators are fundamental to Python programming (and programming as a whole); they allow us to manipulate data and control the flow of our code. Understanding how to use operators effectively enables programmers to write code that accomplishes a desired task.

In more specific terms, an operator takes two elements – called operands – and combines them in a given manner. The specific way that this combination happens is what defines the operator. For example, the operation A + B takes the operands A and B , performs the “sum” operation (denoted by the + operator), and returns the total of those two operands.

The Complete List of Python Operators

Now that we know the basic theory behind Python operators, it’s time to go over every single one of them.

In each section below, we will explain a family of operators, provide a few code samples on how they are used, and present a comprehensive table of all operators in that family. Let’s get started!

Python Arithmetic Operators

Arithmetic operators are used to perform mathematical calculations like addition, subtraction, multiplication, division, exponentiation, and modulus. Most arithmetic operators look the same as those used in everyday mathematics (or in spreadsheet formulas).

Here is the complete list of arithmetic operators in Python:

+

Addition

2 + 3

5

-

Subtraction

5 - 2

3

*

Multiplication

4 * 6

24

/

Division

11 / 4

2.75

//

Floor division

11 // 4

2

%

Modulo ( )

11 % 4

3

**

Exponentiation ( )

2 ** 3

8

Most of these operators are self-explanatory, but a few are somewhat tricky. The floor division operator ( // ), for example, returns the integer portion of the division between two numbers.

The modulo operator ( % ) is also uncommon: it returns the remainder of an integer division, i.e. what remains when you divide a number by another. When dividing 11 by 4, the number 4 divides “perfectly” up to the value 8. This means that there’s a remainder of 3 left, which is the value returned by the modulo operator.

Also note that the addition ( + ) and subtraction ( - ) operators are special in that they can operate on a single operand; the expression +5 or -5 is considered an operation in itself. When used in this fashion, these operators are referred to as unary operators . The negative unary operator (as in -5 ) is used to invert the value of a number, while the positive unary operator (as in +5 ) was mostly created for symmetrical reasons, since writing +5 is effectively the same as just writing 5 .

Python Assignment Operators

Assignment operators are used to assign values to variables . They can also perform arithmetic operations in combination with assignments.

The canonical assignment operator is the equal sign ( = ). Its purpose is to bind a value to a variable: if we write x = 10 , we store the value 10 inside the variable x. We can then later refer to the variable x in order to retrieve its value.

The remaining assignment operators are collectively known as augmented assignment operators . They combine a regular assignment with an arithmetic operator in a single line. This is denoted by the arithmetic operator placed directly before the “vanilla” assignment operator.

Augmented assignment operators are simply used as a shortcut. Instead of writing x = x + 1 , they allow us to write x += 1 , effectively “updating” a variable in a concise manner. Here’s a code sample of how this works:

In the table below, you can find the complete list of assignment operators in Python. Note how there is an augmented assignment operator for every arithmetic operator we went over in the previous section:

=

Assign a value to a variable

x = 5

N/A

+=

Add and assign

x += 3

x = x + 3

-=

Subtract and assign

x -= 2

x = x - 2

*=

Multiply and assign

x *= 4

x = x * 4

/=

Divide and assign

x /= 2

x = x / 2

%=

Modulo and assign

x %= 3

x = x // 3

//=

Floor divide and assign

x //= 2

x = x % 2

**=

Exponentiate and assign

x **= 2

x = x ** 2

Python Comparison Operators

Comparison operators are used to compare two values . They return a Boolean value ( True or False ) based on the comparison result.

These operators are often used in conjunction with if/else statements in order to control the flow of a program. For example, the code block below allows the user to select an option from a menu:

The table below shows the full list of Python comparison operators:

==

Equal to

2 == 2

True

!=

Not equal to

3 != 4

True

Greater than

5 > 10

False

Less than

2 < 6

True

>=

Greater than or equal

4 >= 5

False

<=

Less than or equal

2 <= 2

True

Note: Pay attention to the “equal to” operator ( == ) – it’s easy to mistake it for the assignment operator ( = ) when writing Python scripts!

If you’re coming from other programming languages, you may have heard about “ternary conditional operators”. Python has a very similar structure called conditional expressions, which you can learn more about in our article on ternary operators in Python . And if you want more details on this topic, be sure to check out our article on Python comparison operators .

Python Logical Operators

Logical operators are used to combine and manipulate Boolean values . They return True or False based on the Boolean values given to them.

Logical operators are often used to combine different conditions into one. You can leverage the fact that they are written as normal English words to create code that is very readable. Even someone who isn’t familiar with Python could roughly understand what the code below attempts to do:

Here is the table with every logical operator in Python:

and

Returns True only if Boolean values are True; otherwise returns False

(10 > 5) and (10 < 50)

True

(True  ) and (True   )

or

Returns True if value is True; otherwise returns False

(1 < 0) or (1 < 100)

False

(False) or (True  ) 

not

Returns True if the value is False (and False if it is True)

not (10 > 5)

False

not (True  )

Note: When determining if a value falls inside a range of numbers, you can use the “interval notation” commonly used in mathematics; the expression x > 0 and x < 100 can be rewritten as 0 < x < 100 .

Python Identity Operators

Identity operators are used to query whether two Python objects are the exact same object . This is different from using the “equal to” operator ( == ) because two variables may be equal to each other , but at the same time not be the same object .

For example, the lists list_a and list_b below contain the same values, so for all practical purposes they are considered equal. But they are not the same object – modifying one list does not change the other:

The table below presents the two existing Python identity operators:

is

Returns True if both variables are the same object

x is y

is not

Returns True if both variables are not the same object

x is not y

Python Membership Operators

Membership operators are used to test if a value is contained inside another object .

Objects that can contain other values in them are known as collections . Common collections in Python include lists, tuples, and sets.

in

Returns True if the value is in the collection

3 in [1, 2, 3]

True

not in

Returns True if the value is not in the collection

4 not in [1, 2, 3]

True

Python Bitwise Operators

Bitwise operators in Python are the most esoteric of them all. They are used to perform bit-level operations on integers. Although you may not use these operators as often in your day to day coding, they are a staple in low-level programming languages like C.

As an example, let’s consider the numbers 5 (whose binary representation is 101 ), and the number 3 (represented as 011 in binary).

In order to apply the bitwise AND operator ( & ), we take the first digit from each number’s binary representation (in this case: 1 for the number 5, and 0 for the number 3). Then, we perform the AND operation, which works much like Python’s logical and operator except True is now 1 and False is 0 .

This gives us the operation 1 AND 0 , which results in 0 .

We then simply perform the same operation for each remaining pair of digits in the binary representation of 5 and 3, namely:

  • 0 AND 1 = 0
  • 1 AND 1 = 1

We end up with 0 , 0 , and 1 , which is then put back together as the binary number 001 – which is, in turn, how the number 1 is represented in binary. This all means that the bitwise operation 5 & 3 results in 1 . What a ride!

The name “bitwise” comes from the idea that these operations are performed on “bits” (the numbers 0 or 1), one pair at a time. Afterwards, they are all brought up together in a resulting binary value.

The table below presents all existing bitwise operations in Python:

&

Bitwise AND

5 & 3

101 & 001

1

|

Bitwise OR

5 | 3

101 | 011

7

^

Bitwise XOR (exclusive OR)

5 ^ 3

101 ^ 011

6

~

Bitwise NOT (complement)

~5

~101

-6

<< 

Left shift

5 << 1

101 << 1

10

>> 

Right shift

5 >> 1

101 >> 1

2

Operator Precedence in Python

Operator precedence determines the order in which operators are evaluated in an expression. Operators with higher precedence are evaluated first.

For example, the fact that the exponentiation operator ( ** ) has a higher precedence than the addition operator ( + ) means that the expression 2 ** 3 + 4 is seen by Python as (2 ** 3) + 4 . The order of operation is exponentiation and then addition. To override operator precedence, you need to explicitly use parentheses to encapsulate a part of the expression, i.e. 2 ** (3 + 4) .

The table below illustrates the operator precedence in Python. Operators in the earlier rows have a higher precedence:

1

Parentheses

( )

2

Exponentiation

**

3

Unary operators, Bitwise NOT

+x, -x, ~x

4

Multiplication, division, and modulo

*, /, //, %

5

Addition and subtraction

+, -

6

Bitwise shifts

<<, >>

7

Bitwise AND

&

8

Bitwise XOR

^

9

Bitwise OR

|

10

Comparison, identity, and membership

<, <=, >, >=, ==, !=, is, is not, in, not in

11

Logical not

not

12

Logical and

and

13

Logical or

or

Want to Learn More About Python Operators?

In this article, we've covered every single Python operator. This includes arithmetic, assignment, comparison, logical, identity, membership, and bitwise operators. Understanding these operators is crucial for writing Python code effectively!

For those looking to dive deeper into Python, consider exploring our Learn Programming with Python track . It consists of five in-depth courses and over 400 exercises for you to master the language. You can also challenge yourself with our article on 10 Python practice exercises for beginners !

You may also like

arithmetic assignment operator in python

How Do You Write a SELECT Statement in SQL?

arithmetic assignment operator in python

What Is a Foreign Key in SQL?

arithmetic assignment operator in python

Enumerate and Explain All the Basic Elements of an SQL Query

PyJourney

7. Basic Python Operators: Arithmetic, Comparison, and Assignment

Diving into Python, one of the most popular programming languages today, it’s crucial to grasp the basics. Operators in Python are the building blocks for performing calculations, making decisions, and storing values. I’ll walk you through the essentials of arithmetic, comparison, and assignment operators, which are foundational for anyone looking to code in Python.

Whether you’re a beginner just starting out or a seasoned coder brushing up on the basics, understanding these operators is key to writing efficient and effective code. From adding numbers to comparing values and assigning data, I’ve got you covered. Let’s unlock the power of Python operators together and make your coding journey a breeze.

Table of Contents

Arithmetic Operators

Python’s arithmetic operators are the backbone of numerical computations in this versatile language. I’ll break them down for you, so you have a clear understanding of how each operator works and where it’s applicable.

Addition and Subtraction

The Addition ( + ) and Subtraction ( - ) operators are straightforward. You’ll use them for adding or subtracting two numbers:

Subtraction

Multiplication and division.

For Multiplication ( * ) and Division ( / ), Python obeys the typical order of operations to ensure accurate results:

Multiplication

Remember, division always produces a float, even if you’re dividing two integers.

Modulus and Exponentiation

Moving on, the Modulus ( % ) operator finds the remainder after division of one number by another. It’s particularly useful in algorithms that require you to determine if a number is even or odd. Meanwhile, the Exponentiation ( ** ) operator raises one number, the base, to the power of another, the exponent:

Exponentiation

Floor division.

Lastly, Floor Division ( // ) divides and rounds down to the nearest whole number:

Mastering these operations is a must for any task that requires mathematical calculations. Whether you’re building financial models or creating games, arithmetic operators are your fundamental tools. Next, let’s move on to another set of operators that are as critical as arithmetic ones: comparison operators. This will help you make decisions in your code based on the data at hand.

When diving into Python, one of the fundamental tools in your programmer’s kit is the addition operator. Simple to use, it’s represented by the + sign and performs exactly what you’d expect—adds together two values. In practice, here’s how it plays out:

Adding integers

Adding floats.

This operator doesn’t just handle numerical data types like integers and floats, it can also concatenate strings and lists, making it extremely versatile:

Concatenating strings

Combining lists.

Furthermore, the addition operator can be used in an augmented assignment format to both add and assign a value to a variable in one expression:

Augmented assignment

It’s important to note that while addition in Python is fairly straightforward, it’s essential to consider the data type of the items you’re working with to avoid errors. For instance, trying to add together a string and an integer will result in a TypeError, as Python expects homogeneity in addition operations.

As you become more skilled with Python, you’ll find that the addition operator is not just about arithmetic. It’s a powerful tool that allows you to accumulate values, construct strings, merge data structures, and much more. Whether you’re calculating sums or constructing complex data payloads, the addition operator remains a reliable ally in your coding endeavors.

Just as the addition operator plays a crucial role in Python, the subtraction operator is equally fundamental for performing arithmetic calculations. Signified by a minus sign ( - ), subtraction in Python allows you to calculate the difference between numbers, and just like addition, can also be used with various data types.

When working with integers and floats , the subtraction operator operates as expected. If I write 10 - 5 , the output will naturally be 5 . However, subtracting a float from an integer, or vice versa, will result in a float: 7 - 2.0 yields 5.0 . It’s simple arithmetic but forms the basis for many complex operations in Python programming.

Interestingly, in the realm of strings and lists, Python does not directly support the subtraction operator. Trying to subtract one string from another, or one list from another, results in a TypeError . This is because the concept of subtraction doesn’t naturally extend to these data types in the same intuitive way as it does for numbers. However, developers often work around this limitation by using other methods to achieve similar outcomes, such as string methods or list comprehension.

Augmented assignment with subtraction is also available in Python. Using -= allows for a value to be subtracted from a variable and the result assigned back to that variable in a single, concise step. For example, I can write x -= 2 and whatever value x held would be decremented by 2 .

Remember, while Python’s subtraction operator might seem straightforward, its application is broad, acting as one of the pillars of mathematical operations in coding. From calculating simple differences to adjusting values on the fly, subtraction is vital for data manipulation and needs to be understood in depth by any aspiring Python programmer.

When it comes to programming in Python, the multiplication operator is as fundamental as it gets. Denoted by the asterisk (*), this operator allows for the product of two numbers, be they integers or floats. Here’s a quick example: if I write 3 * 4 , Python outputs 12 . This same principle applies to floats: 2.5 * 4.0 returns 10.0 .

But multiplication isn’t limited to numbers alone. Python’s flexibility shines when the multiplication operator is applied to strings. For instance, 'Python!' * 3 gives us 'Python!Python!Python!' , repeating the string thrice. It’s important to remember, this operation doesn’t combine separate strings — it repeats the same string multiple times.

Lists see similar benefits. Multiplying a list by an integer repeats the list’s contents. Therefore, [1, 2, 3] * 2 transforms into [1, 2, 3, 1, 2, 3] . This can be particularly useful when initializing a list with a fixed number of identical elements without manually typing them out.

I should point out that Python enforces type consistency when using the multiplication operator. Attempts to multiply incompatible types, like a string by a list, will result in a TypeError . This ensures that you’re aware of the data types you’re working with and helps maintain clean code.

Moreover, Python supports multiplications using external libraries like NumPy, which offer advanced features for array multiplications. In these scenarios, the multiplication operator can perform operations like matrix multiplications and dot products, taking Python’s capabilities well beyond basic arithmetic.

Using multiplication operator with caution is recommended, particularly when applying it to lists, since it could potentially lead to memory issues. Large list operations can consume significant amounts of memory and slow down performance, especially if you’re repeating a substantial list. Hence, always assess the impact on your code’s efficiency and memory usage before running such operations.

When we dive into the world of Python arithmetic, the division operator emerges as a crucial tool for numerical calculations. Python uses the forward slash (/) for division, providing a straightforward way to divide numbers. This operator can handle both integers and floats with ease. Here’s a quick example: if I write 10 / 5 , Python will give me 2.0 . Notice how the result is a float, not an integer. This is because Python automatically converts integer division results into float for more precision.

But what if you’re interested in integer division? That’s where the floor division operator (//) steps in. If I want to divide 10 by 3 and get an integer result without any decimal places, I’d use 10 // 3 , which yields 3 . It effectively rounds down the result to the nearest whole number. It’s paramount to mention that if there’s a negative number involved, floor division will round towards the negative of infinity. This behavior ensures consistency across different arithmetic operations.

Perhaps less commonly discussed but equally important is the modulus operator (%) , which gives us the remainder of a division operation. If I want to know what’s left over when 10 is divided by 3 , 10 % 3 would return 1 .

Knowing how to handle division in Python is particularly vital in data analysis and scientific computations, where precision and the type of division are key. It’s also important to highlight that Python will raise a ZeroDivisionError if you attempt to divide by zero. Hence, checks for zero are critical before performing division operations to prevent runtime errors.

One might also incorporate libraries like NumPy when dealing with arrays or matrices as these can offer more sophisticated functions and handle division in a way that’s optimized for large datasets. The flexibility of these libraries in handling various numerical operations complements the built-in Python division capabilities.

Remember, just like multiplication, division must be approached with an understanding of the data type involved to avoid type inconsistency errors. By keeping these intricacies in mind, you’ll be able to write more efficient and error-free code.

When I delve into Python’s arithmetic operations, the modulo operator often stands out. Represented by the % symbol, the modulo provides the remainder of a division operation rather than the quotient. It’s especially handy in various programming scenarios, such as determining odd or even numbers or iterating over a sequence with wrap-around.

Understanding the Modulo Operator

To use the modulo operator:

Where dividend is the number you’re dividing and divisor is the number by which you’re dividing. For example, 10 % 3 would return 1 because when dividing 10 by 3, the remainder is 1.

Key Uses of Modulo in Python

  • Looping Techniques : When you need to cycle through a list repeatedly, modulo helps to reset the index.
  • Even: if number % 2 == 0
  • Odd: if number % 2 != 0
  • Time Calculations : Modulo is perfect for converting seconds to minutes and hours, ensuring values stay within calendar bounds.

Unlike division operators, the modulo is less prone to runtime errors like ZeroDivisionError , but you still can’t use zero as a divisor. If attempted, Python will raise a ZeroDivisionError , similar to using the division operator.

Integrating modulo requires mindfulness about operand types — a common theme in Python arithmetic. The result of a modulo operation involving floats can be counterintuitive because we’re often taught to think of remainders in the context of integers.

In cases involving negative values:

The operation considers the sign of the divisor, resulting in 2 , because Python’s modulo returns the remainder closest to zero.

For advanced scenarios, external packages might offer specialized functions. NumPy, for instance, provides a variation of the modulo operator that behaves differently with negative values. Choosing the right tool for each job is critical in programming for efficiency and accuracy.

Whenever I’m faced with a problem requiring the determination of a quotient’s remainder, I make sure the modulo operator is top of mind. It’s a small but mighty tool in Python’s operator arsenal and can be the difference between a good and a great solution. With this knowledge, I can navigate numbers with precision and employ effective strategies for commonly faced challenges in programming.

When diving into Python’s arithmetic operators, we quickly come across the power operator , ** , which is used for exponentiation. This operator raises a number to the power of another, making it an invaluable tool when working with powers and roots in Python.

Let’s take a look at how it’s used:

Raising 2 to the power of 3

In this example, 2 is the base and 3 is the exponent. Python beautifully simplifies what could otherwise be a complex mathematical process into a single line of code.

Understanding the rules and behavior of exponentiation in Python is crucial, especially when dealing with large numbers or when performing precision computing. Here are some key points:

  • Positive exponents : The base is multiplied by itself as many times as the value of the exponent.
  • Negative exponents : Python will return the reciprocal of the base raised to the absolute value of the exponent.
  • Zero exponent : Any base raised to the power of zero will always be 1.

The ** operator isn’t just limited to integers. It can also be used with floats to handle scenarios requiring fractional exponents, which is common in scientific computations:

Square root of 9

Remember though, float operations might introduce rounding errors due to the nature of binary representation in computing. It’s always good practice to be aware of this when expecting precise results.

For more complex mathematical operations that go beyond what Python’s built-in functions offer, you might want to look into modules like math or numpy . These libraries have optimized functions for exponentiation and other intricate mathematical computations that ensure accuracy and efficiency.

As we continue to explore operators, it’s essential to practice using them in real-world problems that require exponentiation. There are countless applications, from calculating compound interest to transforming datasets in data science projects. Empowering yourself with the power operator opens up a universe of possibilities in Python programming.

When working with division in Python, you’ll inevitably come across the Floor Division operator, denoted by a double forward slash // . Unlike the standard division operator / that returns a floating-point result, floor division rounds down the result to the nearest whole number.

Let’s take a deeper dive into why floor division is crucial for certain calculations. One of the primary uses of floor division is to get an integer quotient from the division of two numbers. For instance, if you’re dividing 7 by 2 using the standard division operator, the result would be 3.5. However, with floor division, the result is simply 3 .

Here are a few scenarios where floor division is particularly handy:

  • Allocating resources evenly and determining leftovers
  • Working with time calculations , where decimal parts don’t make sense
  • Processing images or graphics by ensuring pixel counts remain whole numbers

Consider this code snippet for a better understanding:

It’s important to note that when dealing with negative numbers, floor division can have surprising results. For example:

Although -11 / 3 would typically yield approximately -3.6667, floor division will round this down to -4 . This behavior keeps the floor division consistent, always rounding towards minus infinity, which can be essential for maintaining predictable results in your code.

Using floor division in Python is an easy way to keep your calculations integer-based when needed. Integrating this operator into your toolbox can save time and additional steps, especially when working with loops or array indices where non-integer values could cause errors. Remember to test your code with a variety of inputs to understand how floor division operates across different scenarios.

Comparison Operators

When coding in Python, Comparison Operators are the bread and butter for making decisions. These operators allow me to compare two values and, based on the comparison, return a Boolean value of either True or False .

The Common Comparison Operators Are:

  • == : Equal to
  • != : Not equal
  • > : Greater than
  • < : Less than
  • >= : Greater than or equal to
  • <= : Less than or equal to

These operators are fundamental for control flow, enabling functions like if statements and while loops to make logical decisions. For example, I’ll compare user input to a set value to determine the next steps in a program.

Practical Uses of Comparison Operators

In real-world scenarios, I find comparison operators particularly useful when sorting items, validating user input , or implementing algorithms that require condition checking. They’re also crucial while filtering data , such as when I need to extract specific information from large datasets.

Avoiding Common Pitfalls

A common mistake I can make when using comparison operators is confusing the ‘equal to’ operator == with the assignment operator = . It’s vital to ensure that I’m using the correct operator to avoid unexpected behavior in my code. Another issue to watch out for is the mix-up between is and == . While is checks if two variables point to the same object, == evaluates if the values they hold are the same. This distinction is significant when working with mutable objects like lists.

Mastery Through Practice

The more I work with comparison operators, the more intuitive they become. I often incorporate various comparison operations in my practice exercises to get a solid grasp of each operator’s nuances. By combining comparison operators with logical ones like and , or , and not , I can craft complex conditions that can handle multifaceted scenarios in my programs.

Understanding the ‘equal to’ operator in Python is crucial for carrying out effective comparisons. The operator is denoted by two equal signs (==) and is used to determine whether two values are identical. When it comes to programming logic, this operator plays a pivotal role.

Consider a situation where I need to validate user input . I’d use the ‘equal to’ operator to compare the input with a predefined correct answer. If the user’s answer matches the correct answer, the operation evaluates to True .

Here’s a simple code snippet to illustrate its use:

In the code above, if the user_input matches secret_code , the message “Access Granted!” is displayed. Otherwise, the user sees “Access Denied!”

It’s also vital to remember that the ‘equal to’ operator checks for value equality, not identity. Object identity, or whether two variables point to the same object in memory, is checked using the is operator .

Here’s how you shouldn’t confuse ‘equal to’ with the assignment operator:

  • Assignment operator ( = ): Assigns a value to a variable.
  • Equal to operator ( == ): Compares two values for equality.

Moreover, when working with floating-point numbers, programmers need to be cautious of precision issues . Due to the way computers represent floating-point numbers, two values that seem identical may not be considered equal. Always validate such comparisons within a tolerance level or use the math.isclose() function for comparing floating-point numbers.

Using the ‘equal to’ operator effectively requires a firm grasp of the types of data being compared. Always ensure the operands are comparable and understand how Python treats different data types during comparison. For instance, comparing a string with an integer using ‘equal to’ will result in False because their data types are different.

In my next section, I’ll delve into another comparison operator that is often used side by side with ‘equal to’: the ‘not equal to’ operator.

Not Equal To

While the ‘equal to’ operator checks for similarity, the ‘not equal to’ operator serves the opposite function. Represented by an exclamation point followed by an equal sign (!=) , it determines if two values are different. I often use this operator when I need to execute a block of code only if a certain condition is not met. For instance, when dealing with user input, it’s crucial to ensure the input doesn’t match something specific, like a forbidden password or username.

Here’s a simple scenario:

In this example, the != operator saves the day by preventing users from choosing a restricted username. This safeguard is as vital as allowing correct inputs, especially when considering security implications.

Handling Data Types is another area where the ‘not equal to’ operator comes into play. Since Python is dynamically typed, you don’t always know what data types you’ll receive. So, checking for inequality also requires an understanding of how Python compares different data types. When Python compares an integer and a floating-point number, even if their mathematical values are the same, the != operator will consider the different types and may not behave as expected.

It’s especially important to Test Thoroughly when working with != . Situations involving collections like lists and dictionaries might not be straightforward, as the operator checks for inequality between all elements, potentially leading to confusion if not used correctly. Consider how Python treats different container types:

  • Lists: Element by element comparison
  • Dictionaries: Pair by pair (key and value) comparison

When you master the ‘not equal to’ operator, you enhance your error handling and control flow capabilities dramatically. This improvement leads to more robust and reliable code.

Greater Than

In the universe of Python’s comparison operators, the Greater than symbol > stands tall. It’s straightforward yet potent, enabling me to compare two values and determine if one is larger than the other. This operator is commonly used in control structures like if statements and loops, where decisions hinge on numerical comparisons.

When I apply the > operator, Python does what you’d expect – it checks to see if the value on the left is indeed greater than the value on the right. For instance, if I’ve got two variables, age1 set to 30 and age2 set to 25, writing age1 > age2 would yield True because 30 is, in fact, greater than 25. But the practical applications go far beyond just comparing simple integers.

Imagine working on a piece of code where I need to filter a list of items based on their prices. I’ll loop through each item and use the > operator to select only those whose price exceeds a certain threshold. This kind of operation is crucial in tasks like data analysis, where I’m often sieving through vast quantities of data to find significant figures.

  • Syntax: value1 > value2
  • Returns: True if value1 is greater than value2 , otherwise False

It’s also important to be aware of how Python handles comparisons between different data types. For example, comparing an integer to a float works seamlessly since Python knows how to interpret these kinds. However, using the > operator between incompatible types, such as an integer and a string, throws a TypeError. Intuitively, it’s comparing apples to oranges, which Python wisely refrains from.

In complex structures like dictionaries, I need to be more careful. Since dictionaries can hold various data types as values, ensuring I’m comparing items of the same type is imperative. Oftentimes, I’d have to iterate over the dictionary’s values and, based on context, apply the > operator to the elements that I can fairly compare.

Leveraging the > operator intelligently can propel condition-based logic to work precisely as I intend. It’s a cornerstone in building robust Python scripts that respond dynamically to varying data.

Just as crucial as the ‘greater than’ operator, the ‘less than’ operator in Python is denoted by the symbol < . This operator assesses whether the left-hand operand is smaller than the right-hand operand. It returns a boolean value – True if the assertion is correct and False otherwise.

Useful in various programming scenarios , the ‘less than’ operator is fundamental when sorting algorithms are in play or when we need to impose a threshold. Here are some common applications:

  • Imposing limits within loops
  • Conditional expressions in if statements
  • Filtering data during analysis

I use the ‘less than’ operator with numbers predominantly, but it’s versatile with other compatible types in Python, such as strings which are compared based on their alphabetical order.

When comparing strings with numbers , however, Python will raise a TypeError . It’s vital to ensure compatibility between the data types to prevent any unintended errors in the code. Keep in mind that specific comparisons involving complex data structures might require casting or additional checks for a smooth experience.

Up next, I’ll tackle the versatile yet simple assignment operators. Thriving in simplicity, these operators play a pivotal role in almost every aspect of a Python script. From variables initialization to the reassignment of values, assignment operators maintain state and control flow within a program, proving their indispensability in the realm of Python coding.

Greater Than or Equal To

When I’m programming in Python, the ‘greater than or equal to’ operator (>=) is equally essential as its counterpart. It’s used to compare two values, checking not only if one value is greater than the other but also if they’re equal. This operator is particularly useful when setting boundary conditions or ranges within my code.

Let’s explore its application with a real-world example . Imagine I’m writing a program that determines if a user is eligible for a senior discount. The eligibility age is 65 or older.

Here, I’m using the >= operator to check if the age entered is 65 or more. If the condition is true, the message ‘Eligible for discount’ is printed.

Moving beyond simple comparisons, the ‘greater than or equal to’ operator is vital in loop structures . For instance, consider processing a list of scores to determine how many are above a certain threshold:

print(f”Scores above threshold: {above_threshold}”)

In this snippet, each score is checked against the threshold, and the counter increases for each score that meets the condition.

Just as with the ‘less than’ operator, ensuring data type compatibility is crucial. Remember, comparing a string and an integer with >= could lead to errors. To maintain the integrity of my programs I ensure the variables in comparison are of the same or coercible types. This prevents unexpected behavior and promotes reliable code execution.

Like the threads of a tapestry, these operators interweave to form the logic of our Python script, making them indispensable tools in my arsenal for crafting efficient and effective code.

As I familiarize myself with these operators I find my scripts growing not only more sophisticated but also more robust. Stepping through each one, the journey through Python’s basic operators continues to unfold, revealing the simplicity and power of the language.

Less Than or Equal To

Just as important as the ‘greater than or equal to’ operator in Python is the ‘less than or equal to’ operator. This operator is denoted by <= and serves a critical role in programming—especially when you need to evaluate whether a value falls below or exactly at a certain threshold. For example, when managing inventory, confirming that stock levels are sufficient before processing a sale is essential. Here’s how it’s used:

In this snippet, Python checks if the order_quantity is less than or equal to stock . If the order quantity is 10 or less, the condition is true, and we proceed to process the order.

Understanding <= in Different Contexts

The <= operator isn’t limited to simple numerical comparisons—it’s also effective in other contexts:

  • String Comparison : Strings are compared lexicographically in Python, so you can check if one precedes another alphabetically.
  • Date Comparison : When working with date objects, <= ensures that an event occurs before or on a certain date.

Practical Applications of <=

I’ve observed that the use of <= spans a variety of applications:

  • Setting thresholds in game development to trigger an event
  • Validating user input to ensure it doesn’t exceed a limit
  • Analyzing datasets to filter entries based on a condition

It’s crucial to remember that the data types on either side of the <= must be compatible to avoid a TypeError .

Applying the ‘less than or equal to’ operator within loops and conditional statements allows for more complex decision-making processes:

This loop will only print numbers that are 5 or less, demonstrating how <= can control the flow of a program. As you can see, employing <= alongside other Python operators enhances the control and precision we have over our code. With this understanding, you’ll be able to craft more intricate and reliable Python programs that handle a multitude of scenarios effectively.

Assignment Operators

Assignment operators in Python are the foundation of variable management and data storage. These operators are used to assign values to variables . The most common assignment operator is the = sign, which might seem straightforward but is the workhorse of just about any Python program. For instance, when I create a variable to keep track of a score in a game, I use the = to set its initial value: score = 0 .

Beyond the basic assignment, Python also provides a suite of compound assignment operators that combine arithmetic operations with assignment. These are incredibly handy for modifying variable values efficiently. They not only make code cleaner and easier to read but often reduce the chance of typing errors in the process. Here are the main ones I frequently utilize:

  • += for adding and assignment: counter += 1 increments the counter by one.
  • -= for subtraction and assignment: health -= damage subtracts damage from health.
  • *= for multiplication and assignment: price *= discount applies a discount to the price.
  • /= for division and assignment: total /= num_items calculates the average price per item.

In Python, these operators do more than just reduce the amount of typing. For example, they can streamline loop operations or increment counters within a loop without having to write out the full assignment. This can make a significant difference in the readability and performance of the code. Let’s say I’m processing a list of numbers to get a total:

Here, the += operator is effortlessly increasing the total with each iteration. Additionally, in scenarios where I’m working with mutable data types like lists, these operators allow for the modification of data in place, which can lead to more memory-efficient code .

Moreover, Python’s assignment operators support chaining , which brings another layer of elegance to variable management. For example, I can initialize multiple variables at once: x = y = z = 0 . It’s also worth noting that Python 3.8 introduced the walrus operator := , which assigns values within an expression, further expanding the realms of assignment possibilities.

Simple Assignment

In mastering Python, Simple assignment is an essential tool in your programming arsenal. It’s the most straightforward form of assigning a value to a variable. You’ve already seen the = operator in action, which serves as the backbone for variable creation and manipulation in the language.

When I use simple assignment, I follow the basic syntax where the variable name comes first, followed by the = sign, and then the value I wish to assign. Here’s an easy-to-understand example:

In this case, my_variable now holds the value 10 . It’s a clear, concise method that underpins virtually every Python program I write. Additionally, Python allows for multiple assignments in a single line, further simplifying the code:

Here, x , y , and z are assigned to 1 , 2 , and 3 , respectively. It’s a handy shortcut that I often use to initialize several variables at once.

But simple assignment isn’t just about initializing; it’s also used for reassigning values . If I decide that my_variable needs a new value, a simple reassignment does the trick:

my_variable holds 30 instead of 10 . It’s crucial to remember that in Python, variables are just labels pointing to objects, and reassignment doesn’t affect the object originally referenced; it merely attaches the label to a new object.

Furthermore, Python uses dynamic typing , which means that I don’t need to declare the data type of a variable beforehand. This contrasts with statically-typed languages, in which variable types must be explicitly stated. Dynamic typing allows for more flexibility and quicker coding—Python figures out the data type on its own:

Initially, dynamic_var starts as an integer with any numerically assigned value but can just as quickly be reassigned to hold a string. This flexibility is one of Python’s strengths, making it an excellent choice for rapid development and iterative coding processes.

Addition Assignment

Shifting gears from simple assignment, let’s delve into addition assignment. In Python, the += operator does more than just add two numbers together; it’s used to add a value to a variable, updating the variable itself in the process. If I have a variable x and I want to increase its value by 10, I’d simply write x += 10 . This is equivalent to x = x + 10 but far more succinct.

What makes addition assignment invaluable is its ability to streamline code. Think about running totals or iterative updates in a loop – that’s where += shines. It’s not just beneficial for numbers; I’ve frequently used addition assignment with strings to concatenate additional text.

Here’s a quick glimpse:

This code snippet would output Hello, World! , demonstrating how += appends text to an existing string.

Common use cases for addition assignment in practical coding scenarios include:

  • Accumulating values in counters or sums
  • Updating the value of a variable in response to events
  • Concatenating strings or lists over multiple iterations

It’s important to note that addition assignment is part of a broader category of compound assignment operators . These operators include others like subtraction assignment ( -= ), multiplication assignment ( *= ), and division assignment ( /= ), each performing a similar update-in-place for their respective operations.

One aspect of addition assignment that’s often overlooked is its atomicity in single-threaded scenarios. When I use x += 1 , it’s a near-guarantee that x will be incremented by exactly one without the risk of interference from other operations, making it safer in certain applications over a separated statement like x = x + 1 .

Embracing addition assignment helps in writing more efficient and readable code . It’s a small piece of syntax that eloquently embodies Python’s philosophy of simplicity and elegance in programming.

Subtraction Assignment

Following the theme of compound assignment operators, let’s delve into subtraction assignment, another handy operator that Python programmers frequently use. Similar to addition assignment, subtraction assignment uses the -= operator to subtract a value from a variable and then update that same variable in one succinct step. Subtraction assignment is particularly useful when you need to decrease the value of a variable incrementally, such as when tracking decrements in a loop or managing a countdown.

Practical applications of subtraction assignment are easy to spot in day-to-day coding scenarios. For instance, imagine you’re developing a basic game where the player’s health decreases with each enemy encounter. Here’s how subtraction assignment simplifies the code:

player_health -= enemy_damage

By employing subtraction assignment, you avoid the more verbose and less intuitive player_health = player_health - enemy_damage , making the code cleaner and more maintainable.

More than just a convenient shortcut, subtraction assignment can knock out a few processor cycles, optimizing performance at a micro level. This might not stand out in smaller scripts, but when you’re dealing with large-scale applications, every bit of efficiency counts.

Subtraction assignment plays well within the bounds of atomicity in certain contexts, contributing to safer coding patterns. However, it’s important to note that like all operators, the atomicity of a -= operation isn’t guaranteed across all environments, especially in multi-threaded applications where race conditions might occur.

To master Python, practicing with these operators is essential. They’re not merely shorthand—they represent a deeper understanding of Python’s design philosophy that favors simplicity over complexity. Incorporating subtraction assignment where appropriate will ensure your code is not only functional but also adheres to Python’s ethos, making it both efficient and elegant.

Moving alongside subtraction assignment, multiplication and division assignment operators offer similar benefits with their unique twists…

Multiplication Assignment

Moving on to multiplication assignment in Python, we encounter the *= operator. This operator functions similarly to subtraction assignment but focuses on multiplying the current value of a variable by another and then updating the variable. Just like subtraction assignment, multiplication assignment streamlines code , making it more readable and efficient. Here’s how you can put it to use:

my_number is now 15

In the above example, my_number originally holds the value of 5. After applying my_number *= 3 , the value of my_number becomes 15. This tool is particularly useful when dealing with iterative multiplication within loops.

One must keep in mind that multiplication assignment can lead to unexpected results when used with mutable data types, such as lists. For instance, using *= on a list will repeat the elements in that list:

my_list is now [1, 2, 3, 1, 2, 3]

This convenience comes with the same caveats as subtraction assignment. Atomicity isn’t assured, especially in multi-threaded applications where race conditions might affect the value of the variable before the operation takes place.

Just as subtraction assignment simplified decrementing a value, multiplication assignment makes incrementing values exponentially a succinct operation. It ensures that code isn’t cluttered with long-winded expressions, adhering to Python’s philosophy that “Readability counts”. Practicing these operators allows programmers to harness their true potential, enabling one to write concise and clearly structured code.

While multiplication assignment is ideal for numerical calculations , it also plays a significant role in creating repeated sequences or extending lists within your programs. Implementing the *= operator pushes the envelope on what can be achieved with a single line of Python code, reminding us that sometimes, powerful solutions are just an operator away.

Division Assignment

In Python programming, Division assignment is another operation that streamlines the process of dividing a variable by a number and then updating that variable with the new value. Just like multiplication assignment, division assignment uses a compound operator, which is /= . This operator takes the variable on its left, divides it by the expression on its right, and then assigns the result back to the originally named variable.

Consider the scenario where I have a variable defining a quantity of items and I’d like to split these items evenly among a certain number of people. Instead of using two lines of code—one to divide and another to assign the result—I can simply employ the /= operator to perform both actions simultaneously. Here’s how it’s done:

After this operation, the items variable would contain the value 24, precisely what you’d expect after dividing 120 by 5. Easy and efficient, isn’t it?

It’s important to highlight that the division assignment operator in Python always performs floating-point division . This means that even when dividing two integers, the result will be a float . If an integer result is needed, you’d have to manually convert the outcome back to an integer using the int() function or use the floor division assignment operator //= .

However, when using division assignment, a key thing to be cautious about is ZeroDivisionError . This error occurs if the right-hand side of the assignment is zero. In real-world applications, it’s always smart to implement error handling to catch and address such potential issues:

While division assignment is extremely useful, it’s also vital to keep in mind that this operator modifies the variable in-place. If the variable is shared across different parts of a program or among multiple threads, one must consider the implications of altering its value through division assignment to avoid unexpected behaviors or conflicts.

Modulo Assignment

When working with Python, I often find the modulo assignment operator as a secret weapon for certain tasks. Modulo assignment `%=“ combines the modulo operation with assignment in one step. This operator takes the current value of a variable, performs a modulo operation with the specified value, and then updates the variable with the result. Here’s how it works in practice:

After executing, my_number becomes 1, because 10 modulo 3 leaves a remainder of 1.

This is particularly useful when I need to:

  • Ensure a Value Stays Within a Range : If I’m iterating over a list and want to wrap around when I reach the end, modulo assignment ensures that my index value never exceeds the list length.
  • Perform Frequent Remainder Operations : In situations like checking for even or odd numbers, calculating residues in math problems or creating checksums, using %= makes the code cleaner and more efficient.

It’s vital to consider the datatype of the variables involved, as modulo assignment with floating-point numbers can lead to unexpected results due to precision issues.

Common errors such as TypeError may occur if I try to use modulo assignment between incompatible data types like strings and integers. For example, my_string %='world' would raise a TypeError because a string cannot be the left operand for this operator.

The beauty of using modulo assignment lies in its ability to simplify code and reduce the chance of mistakes that might happen if I were to split the modulo operation and the assignment into two separate lines. However, like division assignment, I’m cautious to avoid ZeroDivisionError when the right-hand side is zero, which is crucial to keeping my code exception-proof.

Exponentiation Assignment

When I dive into the concept of Exponentiation assignment in Python, it’s evident that it serves a significant role in mathematical operations. This operator combines exponentiation with assignment, streamlining the process of raising a variable to the power of another number. Exponentiation assignment is represented by **= and is a shorthand way to write the operation x = x ** y , where x is the base variable and y is the exponent.

By using this operator, I can conveniently update the value of a variable without needing to type its name multiple times. This is incredibly efficient when dealing with complex calculations or iterating over large datasets . Here’s an example that illustrates its simplicity:

The result would be 125 , as 5 to the power of 3 is 125 . Using exponentiation assignment, the variable x is now updated to hold the value of 125 .

It’s important to remember that while this operator is powerful, it should be used with precision, particularly with floating-point numbers, where results might not be exact due to the nature of binary floating-point representation.

Moreover, just like with modulo assignment, there’s the need to be aware of and prevent any attempt to raise a number to the power of 0 . Not because it will cause an error, since any number to the power of 0 is 1 , but because it might result in unexpected behavior depending on the use case. Ensuring that the data types are correct before performing operations will help to avoid errors and ensure that the code runs as expected.

In practice, exponentiation assignment can be a very handy tool when coding functions that involve exponential growth , such as compound interest calculations or geometric progression. This operator also highlights Python’s design philosophy of readability, making code more concise and readable at a glance.

Floor Division Assignment

When delving into the realm of arithmetic operators in Python, we often encounter the floor division operator // , which divides two numbers and rounds down to the nearest whole number. Combining this with an assignment operator creates the Floor division assignment operator //= , which is both a time-saver and an enhancer of code legibility. This operator effectively changes the value of a variable to the result of the floor division of its current value by another number.

Imagine working with a dataset that requires the normalization of values by batches. Doing this efficiently requires updating each value without introducing a temporary variable. That’s where //= shines. For example, a //= b translates to a = a // b , hence reducing the lines of code and potential for error.

However, it’s crucial to remember that floor division behaves differently with positive and negative numbers. While 9 // 2 will give you 4 , -9 // 2 will result in -5 , since the result is always rounded down to the nearest whole number. This nuance must be kept in mind to avoid unexpected results, especially when working with datasets that may include negative numbers.

Floor division assignment also plays well with integer and floating-point numbers. Precision may vary with floating-point numbers, so confirming the accuracy of results is always good practice.

In scenarios involving repeated halving or distribution of elements into bins, //= remains a beneficial tool. Whether you’re rounding down timestamps to the nearest minute, or partitioning resources, it provides a straightforward, readable approach to in-place arithmetic operations.

Python’s emphasis on readability and simplicity is echoed throughout its operator suite – and the floor division assignment operator is a testament to that. It streamlines mathematical operations while maintaining clarity, an essential trait for writing clean and maintainable code .

I’ve taken you through the essentials of Python’s arithmetic, comparison, and assignment operators, highlighting the floor division assignment operator’s role in streamlining your code. Remember, while it’s a powerful tool for batch normalization, it’s crucial to be mindful of its behavior with different number types. With these operators in your toolkit, you’re now better equipped to write more concise and readable Python scripts. Embrace these fundamentals, and you’ll see your coding efficiency soar.

Assignment Operators

Add and assign, subtract and assign, multiply and assign, divide and assign, floor divide and assign, exponent and assign, modulo and assign.

to

to and assigns the result to

from and assigns the result to

by and assigns the result to

with and assigns the result to ; the result is always a float

with and assigns the result to ; the result will be dependent on the type of values used

to the power of and assigns the result to

is divided by and assigns the result to

For demonstration purposes, let’s use a single variable, num . Initially, we set num to 6. We can apply all of these operators to num and update it accordingly.

Assigning the value of 6 to num results in num being 6.

Expression: num = 6

Adding 3 to num and assigning the result back to num would result in 9.

Expression: num += 3

Subtracting 3 from num and assigning the result back to num would result in 6.

Expression: num -= 3

Multiplying num by 3 and assigning the result back to num would result in 18.

Expression: num *= 3

Dividing num by 3 and assigning the result back to num would result in 6.0 (always a float).

Expression: num /= 3

Performing floor division on num by 3 and assigning the result back to num would result in 2.

Expression: num //= 3

Raising num to the power of 3 and assigning the result back to num would result in 216.

Expression: num **= 3

Calculating the remainder when num is divided by 3 and assigning the result back to num would result in 2.

Expression: num %= 3

We can effectively put this into Python code, and you can experiment with the code yourself! Click the “Run” button to see the output.

The above code is useful when we want to update the same number. We can also use two different numbers and use the assignment operators to apply them on two different values.

codingem.com

software development and tech.

Python Arithmetic Operators: A Complete Guide (50+ Examples)

In Python, there are 7 arithmetic operators you can use to perform basic mathematical operations.

Here is a table of all the arithmetic operators in Python with examples:

OperatorNameUse
+Additionx + y
Subtractionx – y
*Multiplicationx * y
/Divisionx / y
%Modulusx % y
**Exponentiationx ** y
//Floor divisionx // y

This table is a quick cheat sheet.

However, there are so many things you can do with arithmetic operators in Python. In this guide, you are going to learn how to use arithmetic operators extensively.

Before we start, let’s quickly learn what arithmetic precedence and precedence groups mean:

Precedence Groups

When there are multiple arithmetic operations chained together, the Python compiler needs to know which ones to evaluate first.

This is where precedence is used.

The precedence group of the arithmetic operator specifies in which order expressions are evaluated.

Here is the precedence grouping of the arithmetic operators in Python. The upper the operator is on the table, the higher the precedence.

OperatorsMeaning
Parentheses
Exponent
, , , Multiplication, Division, Floor division, Modulus
, Addition, Subtraction

Now that you understand what is precedence, it is time to jump into the arithmetic operators in Python.

In Python, you can add two numeric values together using the addition operator (+).

For example:

The += Operator

When adding variables, you can combine the addition operator (+) with the assignment operator (=) to form the addition assignment operator (+=).

This is a shorthand for:

The addition operator (+) belongs to the lowest precedence group with subtraction.

This means any other arithmetic operations are carried out first.

Here 2 * 3 is calculated before adding it to 1.

In other words, the Python compiler sees the above expression as:

Where any expressions inside the parenthesis are calculated first.

Now you understand the basics of the addition operator in Python.

Next, let’s take a look at the more advanced use of addition.

The __add__() Method

In Python, you can add numeric types together to produce a new numeric value that represents the sum of the two.

This is made possible by the __add__() method that is implemented behind the scenes.

As a matter of fact, whenever you use the + operator, you are actually calling the __add__() method of the object.

You can verify that this is the case by running a simple experiment:

Understanding this is useful in a moment.

In Python, you can create a custom type by implementing a class that specifies the type.

For example, let’s create a Weight class:

Now, let’s see what happens when you try to add two Weight objects together:

This results in an error:

The error says you cannot use + on two Weight objects.

This is not a surprise.

How could the Python interpreter even know what it means to add two weights together?

But there is a way for you to make this work.

To support addition with custom types in Python, implement the __add__() method into the custom class.

For instance, let’s make it possible to add Weight objects together by summing the kilos of the objects:

The __add__() method takes two Weight objects:

  • self , the left-hand side of the operation.
  • otherWeight , the right-hand side of the operation.

It then sums up the kilos of the weights, creates a new Weight object, and returns it.

Now you can add two Weight objects together to create larger Weight objects, for example:

Pretty handy, isn’t it?

Now you understand how to add two custom objects together in Python using the __add__ method.

But what if the left-hand side and the right-hand side objects are not of the same type?

Adding Different Types

Let’s try to add a Weight object and an int :

This results in the following error:

This is because we have not specified what happens when adding a Weight to another object, such as to an int .

To support adding different types, you need to extend the implementation of the __add__() method:

  • If the right-hand side is an int , we can directly add it to the kilos of the Weight object.
  • If the right-hand side is not an int , we assume it is a Weight . Thus, we need to access the kilos before adding them to the left-hand side.

Here is what the updated class looks like:

Now you can add Weight objects and ints together:

But there is a small problem.

When you reverse the order of the addition:

There is an error, even though one would expect it to work:

Now, let’s think about why this happens.

As you now know, calling a + b is the same as calling a.__add__(b) .

In the failing piece of code, you are calling 200 + w1 , that is, (200).__add__(w1) .

Now, this is problematic.

Trying to add a Weight object to an int object does not work because int has no idea about our Weight class. That is to say that the __add__ method in the int class does not handle adding Weight objects.

To overcome this, you would need to modify the native implementation of the int type.

But this is a no-go.

Instead, Python has a built-in __radd__() method you can use to swap the order of the addition.

The __radd__() Method

The __radd__() method stands for “right addition”.

The idea is simple:

  • If a + b fails, call b.__radd__(a) which is implemented such that a + b does not cause problems.

Let’s implement the __radd__() method to the Weight class:

Now you check that it works:

Now that you understand how addition works in Python, let’s move on to subtraction.

Subtraction

In Python, you can subtract two numeric values from one another by using the subtraction operator (-).

The -= Operator

When decrementing variables, you can combine the subtraction operator (-) with the assignment operator (=) to form the subtraction assignment operator (-=).

The subtraction operator belongs to the lowest precedence group with addition.

This means any other arithmetic operations are calculated first.

Here 2 * 3 is calculated before subtracting it from 1.

Let’s have a look at some advanced use of the subtraction operator.

The __sub__() Method

In Python, you can subtract two numeric types from one another to produce a new value that represents the difference between the two.

This is made possible by the __sub__() method behind the scenes.

The working principle is exactly the same as the __add__() method from the previous section.

Whenever you use the – operator, you are actually calling the __sub__() method.

For example, let’s continue with the Weight class implemented in the previous chapter:

Now, let’s see what happens when you try to subtract two Weight objects:

The error says you cannot use – on two Weight objects.

However, there is a way for you to make this work.

To support subtraction with custom types, implement the __sub__() method into the custom class.

For instance, let’s make it possible to subtract Weight objects from one another by subtracting the kilos of the objects:

The __sub__() method takes two Weight objects:

It subtracts the kilos of the weights, creates a new Weight object, and returns it.

Now you can subtract two Weight objects to get the weight difference as a new Weight object:

Subtracting Different Types

Let’s try to subtract an int from a Weight :

This throws an error:

We have not specified what happens when subtracting something else than a Weight from a Weight object. This is why the above piece of code does not work.

To make subtracting different types work, extend the implementation of the __sub__() method:

  • If the right-hand side is an int , we can directly subtract it from the kilos .
  • If the right-hand side is not an int , we assume it is a Weight . Thus, we need to access the kilos before subtracting.

Now it works:

But there is one more problem.

When you reverse the order of the subtraction:

As you now know, calling a – b is the same as calling a.__sub__(b) .

In the above you are calling 150 – w1 , that is, (150).__sub__(w1) .

This is the problem.

Trying to subtract a Weight object from an int object does not work because the built-in int type has no idea about the Weight class.

To overcome the issue, you would need to modify the native implementation of the int type.

But there is a better way to do it.

Instead, Python has a built-in __rsub__() method you can use to swap the order of the subtraction.

The __rsub__() Method

The __rsub__() method stands for “right subtraction”.

The idea of this is easy to understand:

  • If a – b fails, call b.__rsub__(a) which is implemented such that a – b does not cause problems.

Let’s implement the __rsub__() method to the Weight class:

Now you understand how subtraction works in Python.

Also, you may have noticed there is a clear pattern between each arithmetic operator. Each arithmetic operator corresponds to a special method with a double underscore method that is called behind the scenes. This method can be customized for a custom type.

Anyway, let’s continue with multiplication.

Multiplication

In Python, you can multiply two numeric types by using the multiplication operator (*).

The *= Operator

When multiplying variables, you may combine the multiplication operator (*) with the assignment operator (=) to form the multiplication assignment operator (*=).

The multiplication operator belongs to a higher precedence group than addition and subtraction.

This means multiplication takes place before addition or subtraction.

Here is how you can group the operations in your mind:

Where expressions inside the parenthesis are calculated first.

Next, let’s take a look at the more advanced use of multiplication.

The __mul__() Method

In Python, you can multiply numeric types to produce a new value that represents the product of the two. This is made possible by the __mul__() method that is implemented behind the scenes.

As a matter of fact, whenever you use the * operator, you are actually calling the __mul__() method behind the scenes.

You can try it to see how it works:

Now, let’s see what happens when you try to multiply two Weight objects:

The error says you cannot use * on two Weight objects.

How could the Python interpreter even know what it means to multiply two weights?

Anyway, similar to the other arithmetic operators, there is a way to make this work.

To support multiplication with custom types in Python, implement the __mul__() method into the custom class.

For instance, let’s make it possible to multiply Weight objects by multiplying the kilos of the objects:

The __mul__() method takes two Weight objects:

It then multiplies the kilos of the weights, creates a new Weight object, and returns it.

Let’s make sure it works:

Now you understand how to multiply custom types by one another.

Multiplying Different Types

Let’s try to multiply a Weight object by an int :

This happens because it is not specified what happens when multiplying a Weight by another object.

To make multiplying different types work, extend the implementation of the __mul__() method:

  • If the right-hand side is an int , we can directly multiply it by the kilos of the weight.
  • If the right-hand side is not an int , we assume it is a Weight . So we need to access the kilos before the multiplication.

Here is the updated class:

Now multiplying Weights by ints is possible:

Now there is one more issue.

If you reverse the order of the multiplication:

Let’s see why this error happens.

Calling a * b is the same as calling a.__mul__(b) .

Above you are calling 150 * w1 , that is, (150).__mul__(w1) .

Trying to multiply an int object by a Weight does not work because the built-in int type has no idea about the Weight class.

To overcome the issue, you would need to make changes to the native implementation of the int type.

Instead of doing this, Python has a built-in __rmul__() method you can safely implement to swap the order of the multiplication.

The __rmul__() Method

The __rmul__() method stands for “right multiplication”.

The working principle is simple:

  • If a * b fails, call b.__rmul__(a) which is implemented such that a * b does not cause problems.

Let’s implement the __rmul__() method to the Weight class:

Next, let’s take a look at division.

In Python, you can divide two numeric types using the division operator (/).

The /= Operator

When you want to update a variable by dividing it, you can combine the division operator (/) with the assignment operator (=) to form the division assignment operator (/=).

Division operation precedes addition and subtraction.

Here 6 / 3 is calculated before adding it to 1.

Next, let’s take a look at the more advanced use of division.

The __truediv__() Method

In Python, you can divide numeric types to produce a new value that represents the division of the two.

This is made possible by the __truediv__() method that is implemented behind the scenes.

Whenever you use the / operator, you are actually calling the __truediv__() method under the hood.

You can verify this by running a simple test:

In Python, you can create a custom type by implementing a class.

For example, let’s use the Weight class from earlier examples:

Now, let’s divide two Weight objects:

You cannot use / on two Weight objects. This is because the Python interpreter has no idea what division means in the context of Weight .

Anyway, you can change this.

To support the division of custom types in Python, implement the __truediv__() method into the custom class.

For instance, let’s make it possible to divide Weight objects by dividing the kilos properties:

The __truediv__() method takes two Weight objects:

It then divides the kilos of the weights, creates a new Weight object, and returns it.

Let’s test it:

Now it is possible to divide Weight objects by one another.

Dividing Different Types

Let’s try to divide a Weight object by an int :

This is not a surprise because we have not specified what should happen when dividing a Weight by an integer.

To make the division work, extend the implementation of the __truediv__() method:

  • If the right-hand side is an int , we can directly divide it by the kilos of the Weight object.
  • If the right-hand side is not an int , we assume it is a Weight . Then we need to access the kilos before the the division.

Here is how it looks in code:

Now multiplying Weights by ints works:

Now there is still one problem.

When you reverse the order of the division operands:

You are going to see an error:

Let’s see why this happens.

As you already know, calling a / b is the same as calling a.__truediv__(b) .

In the above piece of code, you are calling 150 / w1 , that is, (150).__truediv__(w1) .

This causes the problem.

Trying to divide an int object by a Weight does not work because the built-in int type has no idea about the Weight class.

To fix the problem, you would need to make changes to the built-in int type’s __truediv__ method. But that would be a bad idea.

Instead, Python has a built-in __rtruediv__() method you can use to swap the order of the division.

The __rtruediv__() Method

The __rtruediv__() method stands for “right division”.

It works such that:

  • If a / b fails, call b.__rtruediv__(a) which is implemented such that a / b does not cause problems.

Let’s implement the __rtruediv__() method to the Weight class:

Now you can divide an int by a Weight object.

Next, let’s take a look at the integer division, also known as the floor division.

Integer Division

In Python, you can integer-divide (floor-divide) two numeric types by using the floor division operator (//).

The floor division divides two numbers and rounds the result down to the nearest integer. The result is thus always an integer.

The //= Operator

When floor-dividing variables, you may combine the floor division operator (//) with the assignment operator (=) to form the floor division assignment operator (//=).

The floor division operator belongs to a higher precedence group than addition and subtraction. This means it takes place before addition or subtraction.

Here 10 // 3 is calculated before adding it to 5.

Next, let’s take a look at the more advanced use of floor division in Python.

The __floordiv__() Method

In Python, you can floor-divide numbers to produce an integer that represents the floor division between the two numbers.

Floor division is made possible by the __floordiv__() method that is implemented under the hood.

When you use the // operator, you are actually calling the __floordiv__() method behind the scenes.

In Python, you can write custom types. This happens by implementing a class that acts as a blueprint for creating objects.

For example, let’s use the Weight class from the earlier examples:

When you try to floor-divide two Weight objects:

You receive an error:

The error states you cannot apply // on two Weight objects.

This is not a real surprise. How could the Python interpreter even know what it means to multiply two weights?

Anyway, there is a way to make it work.

To support floor division between custom types in Python, implement the __floordiv__() method into the custom class.

For instance:

The __floordiv__() method takes two Weight objects:

  • self , the left-hand side of the operator.
  • otherWeight , the right-hand side of the operator.

It then floor-divides the kilos properties, creates a new Weight object, and returns it.

Now you understand how to floor-division works for custom types.

Floor-Dividing Different Types

Let’s try to floor divide a Weight object by an int :

This is because you have not specified what happens when floor-divide a Weight by another object.

To make floor-dividing work this way, you need to extend the implementation of the __floordiv__() method:

  • If the right-hand side is an int , we can directly floordivide it by the kilos property.
  • If the right-hand side is not an int , we assume it is a Weight and access the kilos before the division.

Now floor-division between Weights and ints is possible:

Now there is still one small issue.

When you reverse the order of the operands:

There is an error:

As you learned, calling a // b is the same as calling a.__floordiv__(b) .

Above you are calling 150 // w1 , that is, (150).__floordiv__(w1) .

Trying to floor-divide a Weight object by an int does not work because the built-in int type has no idea about the Weight class.

To fix this, you would need to make changes to the native implementation of the int type.

However, instead of doing it that way, Python has a built-in __rfloordiv__() method you can use to swap the order of the floor division.

The __rfloordiv__() Method

The __rfloordiv__() method stands for “right floor division”.

  • If a // b fails, call b.__rfloordiv__(a) which is implemented such that a // b does not cause problems.

With this in mind, let’s implement the __rfloordiv__() method to the Weight class:

Next, let’s take a look at a closely related arithmetic operator, the modulo.

In Python, you can calculate the remainder in division using the modulo operator (%).

For example, let’s divide 15 pizza slices for 6 guests evenly.

The result is 3.

This means 3 slices of pizza will be leftover.

If you think about it, that makes sense.

Sharing 15 slices of pizza evenly to a group of 6 is not possible. However, you can give 2 slices to each person. At this point, you have shared 12 slices out of 15, so there will be 3 slices left.

The %= Operator

You can combine the modulo operator (%) with the assignment operator (=) to form the modulo assignment operator (%=).

This is a useful shorthand for:

The modulo belongs to a precedence group that is higher than addition or subtraction. This means modulo takes place before them.

Next, let’s take a look at the more advanced use of modulo in Python.

The __mod__() Method

Calculating the modulo is possible via the __mod__() method. This method is implemented behind the scenes.

Whenever you use the % operator, you call the __mod__() method behind the scenes.

For example, let’s continue with the Weight class you saw earlier.

Let’s see what happens when you try to modulo two Weight objects:

This shows an error:

You cannot apply % between two Weight objects. This is because the Python interpreter does not know what it means to take modulo between Weight objects.

However, you can separately specify what this means to make it work.

To support modulo between custom types, implement the __mod__() method into the custom class.

For instance, let’s make it possible to take a remainder between Weight objects based on the kilos :

The __mod__() method takes two Weight objects:

  • Calculates the remainder using the kilos of the weights
  • Creates a new Weight object
  • Returns the new Weight object.

It works! However, please notice that this example is pretty useless. It just demonstrates how you can customize the % operator for custom classes in Python.

Now you understand how to calculate modulos between two Python objects.

Calculating Modulo Between Different Types

Let’s try to mod a Weight object with an int :

You have not specified what happens when multiplying a Weight by another object. This is why you see an error.

To make modulo between different types work, extend the implementation of the __mod__() method:

  • If the right-hand side is an int , we can directly calculate the modulo using the kilos of the weight.
  • If the right-hand side is not an int , we assume it is a Weight . So we need to access the kilos before calculating the modulo.

Here is what the updated code looks like:

Now calculating modulo between Weights and ints is possible:

Even though this works, there is still one little problem we need to address.

When you reverse the order, that is, when you try to calculate modulo between int and a Weight :

You see an error:

Calling a % b is the same as calling a.__mod__(b) .

Above you are calling 20 % w1 , that is, (20).__mod__(w1) .

Trying to calculate the modulo between an int and a Weight does not work. This is because the built-in int type has no idea about the Weight class and what to do with it.

To overcome the issue, you would need to make changes to the native implementation of the int type. But as you already know, this is not what you want to do.

Instead, Python has a built-in __rmod__() method you can use to swap the order of the operation.

The __rmod__() Method

The __rmod__() method stands for “right modulo”.

The idea is:

  • If a % b fails, call b.__rmod__(a) which is implemented such that a % b does not cause problems.

Let’s implement the __rmod__() method:

Awesome. Last but not least, let’s take a look at the power operator in Python.

In maths, power means to multiply a number by itself a number of times.

  • 3 2 means 3 * 3.
  • 3 4 means 3 * 3 * 3 * 3.

In Python, you can raise a number to a power using the power operator (**).

  • x is the number to be raised.
  • y is the number of times x is multiplied by itself.

The **= Operator

When raising variables to power, you may combine the power operator (**) with the assignment operator (=) to form the power assignment operator (**=).

In Python, the power operator has the highest precedence of all arithmetic operators.

This means power takes place before multiplication, division, modulo, floor division, addition, or subtraction.

Next, let’s take a look at the more advanced use of powers in Python.

The __pow__() Method

In Python, you can raise numeric types to a power produce a new value that represents the number multiplied by itself a number of times.

The power operation is made possible by the __pow__() method behind the scenes.

Whenever you use the ** operator, you are actually calling the __pow__() method.

This is easy to verify.

For example, let’s continue with the Weight class from the previous chapters:

Now, let’s see what happens when you try to raise a Weight object to the power of another Weight :

Obviously, this results in an error:

The error says you cannot use ** on two Weight objects. This is because the Python interpreter does not know what it means to raise a Weight to the power of another Weight .

Anyway, there is a way to make this work.

To support power with custom types in Python, implement the __pow__() method into the class.

For example, let’s make it possible to raise a Weight object to the power of another Weight via the kilos property:

The __pow__() method takes two Weight objects:

  • Raises the kilos of the weights to powers accordingly
  • Returns the new Weight .

Let’s test that it works:

Now you understand how to raise types to powers in Python.

Raising Different Types to Power

Let’s try to raise a Weight object to the power of an int :

This happens because you have not specified what happens when raising a Weight to the int power.

To make it work, extend the implementation of the __pow__() method:

  • If the right-hand side is an int , we can directly raise the kilos of the weight to the power of the integer value.
  • If the right-hand side is not an int , we assume it is a Weight . So we need to access the kilos before the raising it.

Here is what the code looks like after the updates:

Now you can test it:

Now there is one more problem to be solved.

When you reverse the order, that is, when you try to raise an int to the power of Weight :

You get an error:

Calling a ** b is the same as calling a.__pow__(b) .

Here you are calling 3 ** w1 , that is, (3).__pow__(w1) .

This is problematic because the int type does not know anything about the Weight class.

To overcome the issue, you would need to make changes to the built-in int type. But this would be bad.

Instead, Python has a built-in __rpow__() method you can use to swap the order of the operation.

The __rpow__() Method

The __rpow__() method stands for “right power”.

  • If a ** b fails, call b.__rpow__(a) which is implemented such that a ** b does not cause problems.

With this information, let’s implement the __rpow__() :

This concludes the comprehensive guide on all the arithmetic operators in Python.

Thanks for reading.

Happy coding!

Further Reading

Increment and Decrement Operators in Python

Learn Python practically and Get Certified .

Popular Tutorials

Popular examples, reference materials, learn python interactively, python introduction.

  • Get Started With Python
  • Your First Python Program
  • Python Comments

Python Fundamentals

  • Python Variables and Literals
  • Python Type Conversion
  • Python Basic Input and Output

Python Operators

Python flow control.

Python if...else Statement

  • Python for Loop
  • Python while Loop
  • Python break and continue
  • Python pass Statement

Python Data types

  • Python Numbers and Mathematics
  • Python List
  • Python Tuple
  • Python String
  • Python Dictionary
  • Python Functions
  • Python Function Arguments
  • Python Variable Scope
  • Python Global Keyword
  • Python Recursion
  • Python Modules
  • Python Package
  • Python Main function

Python Files

  • Python Directory and Files Management
  • Python CSV: Read and Write CSV files
  • Reading CSV files in Python
  • Writing CSV files in Python
  • Python Exception Handling
  • Python Exceptions
  • Python Custom Exceptions

Python Object & Class

  • Python Objects and Classes
  • Python Inheritance
  • Python Multiple Inheritance
  • Polymorphism in Python

Python Operator Overloading

Python Advanced Topics

  • List comprehension
  • Python Lambda/Anonymous Function
  • Python Iterators
  • Python Generators
  • Python Namespace and Scope
  • Python Closures
  • Python Decorators
  • Python @property decorator
  • Python RegEx

Python Date and Time

  • Python datetime
  • Python strftime()
  • Python strptime()
  • How to get current date and time in Python?
  • Python Get Current Time
  • Python timestamp to datetime and vice-versa
  • Python time Module
  • Python sleep()

Additional Topic

Precedence and Associativity of Operators in Python

  • Python Keywords and Identifiers
  • Python Asserts
  • Python Json
  • Python *args and **kwargs

Python Tutorials

Python 3 Tutorial

  • Python Strings
  • Python any()

Operators are special symbols that perform operations on variables and values. For example,

Here, + is an operator that adds two numbers: 5 and 6 .

  • Types of Python Operators

Here's a list of different types of Python operators that we will learn in this tutorial.

  • Arithmetic Operators
  • Assignment Operators
  • Comparison Operators
  • Logical Operators
  • Bitwise Operators
  • Special Operators

1. Python Arithmetic Operators

Arithmetic operators are used to perform mathematical operations like addition, subtraction, multiplication, etc. For example,

Here, - is an arithmetic operator that subtracts two values or variables.

Operator Operation Example
Addition
Subtraction
Multiplication
Division
Floor Division
Modulo
Power

Example 1: Arithmetic Operators in Python

In the above example, we have used multiple arithmetic operators,

  • + to add a and b
  • - to subtract b from a
  • * to multiply a and b
  • / to divide a by b
  • // to floor divide a by b
  • % to get the remainder
  • ** to get a to the power b

2. Python Assignment Operators

Assignment operators are used to assign values to variables. For example,

Here, = is an assignment operator that assigns 5 to x .

Here's a list of different assignment operators available in Python.

Operator Name Example
Assignment Operator
Addition Assignment
Subtraction Assignment
Multiplication Assignment
Division Assignment
Remainder Assignment
Exponent Assignment

Example 2: Assignment Operators

Here, we have used the += operator to assign the sum of a and b to a .

Similarly, we can use any other assignment operators as per our needs.

3. Python Comparison Operators

Comparison operators compare two values/variables and return a boolean result: True or False . For example,

Here, the > comparison operator is used to compare whether a is greater than b or not.

Operator Meaning Example
Is Equal To gives us
Not Equal To gives us
Greater Than gives us
Less Than gives us
Greater Than or Equal To give us
Less Than or Equal To gives us

Example 3: Comparison Operators

Note: Comparison operators are used in decision-making and loops . We'll discuss more of the comparison operator and decision-making in later tutorials.

4. Python Logical Operators

Logical operators are used to check whether an expression is True or False . They are used in decision-making. For example,

Here, and is the logical operator AND . Since both a > 2 and b >= 6 are True , the result is True .

Operator Example Meaning
a b :
only if both the operands are
a b :
if at least one of the operands is
a :
if the operand is and vice-versa.

Example 4: Logical Operators

Note : Here is the truth table for these logical operators.

5. Python Bitwise operators

Bitwise operators act on operands as if they were strings of binary digits. They operate bit by bit, hence the name.

For example, 2 is 10 in binary, and 7 is 111 .

In the table below: Let x = 10 ( 0000 1010 in binary) and y = 4 ( 0000 0100 in binary)

Operator Meaning Example
Bitwise AND x & y = 0 ( )
Bitwise OR x | y = 14 ( )
Bitwise NOT ~x = -11 ( )
Bitwise XOR x ^ y = 14 ( )
Bitwise right shift x >> 2 = 2 ( )
Bitwise left shift x 0010 1000)

6. Python Special operators

Python language offers some special types of operators like the identity operator and the membership operator. They are described below with examples.

  • Identity operators

In Python, is and is not are used to check if two values are located at the same memory location.

It's important to note that having two variables with equal values doesn't necessarily mean they are identical.

Operator Meaning Example
if the operands are identical (refer to the same object)
if the operands are not identical (do not refer to the same object)

Example 4: Identity operators in Python

Here, we see that x1 and y1 are integers of the same values, so they are equal as well as identical. The same is the case with x2 and y2 (strings).

But x3 and y3 are lists. They are equal but not identical. It is because the interpreter locates them separately in memory, although they are equal.

  • Membership operators

In Python, in and not in are the membership operators. They are used to test whether a value or variable is found in a sequence ( string , list , tuple , set and dictionary ).

In a dictionary, we can only test for the presence of a key, not the value.

Operator Meaning Example
if value/variable is in the sequence
if value/variable is in the sequence

Example 5: Membership operators in Python

Here, 'H' is in message , but 'hello' is not present in message (remember, Python is case-sensitive).

Similarly, 1 is key, and 'a' is the value in dictionary dict1 . Hence, 'a' in y returns False .

  • Precedence and Associativity of operators in Python

Table of Contents

  • Introduction
  • Python Arithmetic Operators
  • Python Assignment Operators
  • Python Comparison Operators
  • Python Logical Operators
  • Python Bitwise operators
  • Python Special operators

Before we wrap up, let’s put your knowledge of Python operators to the test! Can you solve the following challenge?

Write a function to split the restaurant bill among friends.

  • Take the subtotal of the bill and the number of friends as inputs.
  • Calculate the total bill by adding 20% tax to the subtotal and then divide it by the number of friends.
  • Return the amount each friend has to pay, rounded off to two decimal places.

Video: Operators in Python

Sorry about that.

Our premium learning platform, created with over a decade of experience and thousands of feedbacks .

Learn and improve your coding skills like never before.

  • Interactive Courses
  • Certificates
  • 2000+ Challenges

Related Tutorials

Python Tutorial

theme logo

Logical Python

Effective Python Tutorials

Python Assignment Operators

Introduction to python assignment operators.

Assignment Operators are used for assigning values to the variables. We can also say that assignment operators are used to assign values to the left-hand side operand. For example, in the below table, we are assigning a value to variable ‘a’, which is the left-side operand.

OperatorDescriptionExampleEquivalent
= a = 2a = 2
+= a += 2a = a + 2
-= a -= 2a = a – 2
*= a *= 2a = a * 2
/= a /= 2a = a / 2
%= a %= 2a = a % 2
//= a //= 2a = a // 2
**= a **= 2a = a ** 2
&= a &= 2a = a & 2
|= a |= 2a = a | 2
^= a ^= 2a = a ^ 2
>>= a >>= 2a = a >> 2
<<= a <<= 3a = a << 2

Assignment Operators

Assignment operator.

Equal to sign ‘=’ is used as an assignment operator. It assigns values of the right-hand side expression to the variable or operand present on the left-hand side.

Assigns value 3 to variable ‘a’.

Addition and Assignment Operator

The addition and assignment operator adds left-side and right-side operands and then the sum is assigned to the left-hand side operand.

Below code is equivalent to:  a = a + 2.

Subtraction and Assignment Operator

The subtraction and assignment operator subtracts the right-side operand from the left-side operand, and then the result is assigned to the left-hand side operand.

Below code is equivalent to:  a = a – 2.

Multiplication and Assignment Operator

The multiplication and assignment operator multiplies the right-side operand with the left-side operand, and then the result is assigned to the left-hand side operand.

Below code is equivalent to:  a = a * 2.

Division and Assignment Operator

The division and assignment operator divides the left-side operand with the right-side operand, and then the result is assigned to the left-hand side operand.

Below code is equivalent to:  a = a / 2.

Modulus and Assignment Operator

The modulus and assignment operator divides the left-side operand with the right-side operand, and then the remainder is assigned to the left-hand side operand.

Below code is equivalent to:  a = a % 3.

Floor Division and Assignment Operator

The floor division and assignment operator divides the left side operand with the right side operand. The result is rounded down to the closest integer value(i.e. floor value) and is assigned to the left-hand side operand.

Below code is equivalent to:  a = a // 3.

Exponential and Assignment Operator

The exponential and assignment operator raises the left-side operand to the power of the right-side operand, and the result is assigned to the left-hand side operand.

Below code is equivalent to:  a = a ** 3.

Bitwise AND and Assignment Operator

Bitwise AND and assignment operator performs bitwise AND operation on both the operands and assign the result to the left-hand side operand.

Below code is equivalent to:  a = a & 3.

Illustration:

Numeric ValueBinary Value
2010
3011

Bitwise OR and Assignment Operator

Bitwise OR and assignment operator performs bitwise OR operation on both the operands and assign the result to the left-hand side operand.

Below code is equivalent to:  a = a | 3.

Bitwise XOR and Assignment Operator

Bitwise XOR and assignment operator performs bitwise XOR operation on both the operands and assign the result to the left-hand side operand.

Below code is equivalent to:  a = a ^ 3.

Bitwise Right Shift and Assignment Operator

Bitwise right shift and assignment operator right shifts the left operand by the right operand positions and assigns the result to the left-hand side operand.

Below code is equivalent to:  a = a >> 1.

Numeric InputBinary ValueRight shift by 1Numeric Output
2001000011
4010000102

Bitwise Left Shift and Assignment Operator

Bitwise left shift and assignment operator left shifts the left operand by the right operand positions and assigns the result to the left-hand side operand.

Below code is equivalent to:  a = a << 1.

Numeric InputBitwise ValueLeft shift by 1Numeric Output
2001001004
4010010008

References:

  • Different Assignment operators in Python
  • Assignment Operator in Python
  • Assignment Expressions

Arithmetic operators in Python (+, -, *, /, //, %, **)

This article explains the arithmetic operators in Python.

For numbers, such as integers ( int ) and floating point numbers ( float ), you can perform basic arithmetic operations like addition, subtraction, multiplication, division, and exponentiation. For lists or strings, you can perform operations such as concatenation and repetition.

Addition: the + operator

Subtraction: the - operator, multiplication: the * operator, division: the / operator, integer division: the // operator, division remainder (mod): the % operator, exponentiation: the ** operator, zerodivisionerror, compound assignment operators, operations involving int and float, operator precedence, concatenation: the + operator, repetition: the * operator.

The asterisks * and ** are also used when defining or calling a function to unpack arguments.

  • *args and **kwargs in Python (Variable-length arguments)
  • Unpack and pass list, tuple, dict to function arguments in Python

Arithmetic Operations

The + operator performs addition.

The - operator performs subtraction.

The * operator performs multiplication.

The / operator performs division.

In Python 2, division between integers returned an integer ( int ). Since Python 3, it has returned a floating point number ( float ).

The // operator performs integer division.

If floating point numbers ( float ) are included in the calculation, the result is returned as a float even if it represents an integer value.

The % operator calculates the remainder of division.

As in the above example, floating point numbers ( float ) may introduce numerical errors. See the following article for details.

  • Check if the floating point numbers are close in Python (math.isclose)

There is also the divmod() function that returns the quotient and remainder together.

  • Get quotient and remainder with divmod() in Python

The ** operator performs exponentiation.

You can also calculate the power of floating point numbers and negative values. 0 raised to the power of 0 is defined as 1 .

Division by 0 results in a ZeroDivisionError .

For exception handling, refer to the following article.

  • Try, except, else, finally in Python (Exception handling)

The operators, such as + and - , return a new object. Note that f-strings are used here to output the value of variables.

  • How to use f-strings in Python

Operators that are combined with = sign, like += , are called compound assignment operators. The result is assigned and updated to the object on the left side.

In addition to the += operator, there are the -= , *= , /= , %= , and **= operators.

If a floating point number ( float ) is included in a calculation with the + , - , or * operators, the result is returned as a float , even if it represents an integer value.

In Python 3, the / operator returns a float even if the calculation involves integers and the result is an integer value.

The ** operator returns an int if the calculation involves integers. However, if floating point numbers or negative values are involved, the result becomes a float , even if it represents an integer value.

In Python, the operator precedence follows the same rules as in standard arithmetic.

  • 6. Expressions - Operator precedence — Python 3.11.4 documentation

The following two expressions are equivalent.

If you enclose an expression in parentheses () , that part will be calculated first. This follows the same principle as in standard arithmetic.

Operations on lists, tuples, strings

Arithmetic operators perform specific operations on non-numeric objects.

The + operator performs concatenation on lists, tuples, strings, and other similar types.

Adding incompatible types results in a TypeError . For example, if you want to add a value to a list, you must concatenate it as a list with one element.

Note that a single element tuple requires a comma , at the end.

  • A tuple with one element requires a comma in Python

The compound assignment operator += can also be used.

There are other ways to concatenate lists, tuples, and strings other than the + operator. See the following articles for details.

  • Add an item to a list in Python (append, extend, insert)
  • Concatenate strings in Python (+ operator, join, etc.)

The * operator performs repetition on lists, tuples, strings, etc.

The * operator returns the same result whether an integer is used as the left operand (as in int * list ) or the right operand (as in list * int ).

For objects other than integers ( int ), a TypeError occurs. When using negative integers with the * operator, it returns an empty list, tuple, or string.

The compound assignment operator *= can also be used.

The * operator has a higher priority than the + operator, so the * operation is processed first. Of course, you can also control the processing order with parentheses () .

Related Categories

Related articles.

  • Get the fractional and integer parts with math.modf() in Python
  • pandas: Write DataFrame to CSV with to_csv()
  • pandas: Extract rows that contain specific strings from a DataFrame
  • Set operations on multiple dictionary keys in Python
  • Complex numbers in Python
  • Get the n-largest/smallest elements from a list in Python
  • Convert a list of strings and a list of numbers to each other in Python
  • Wrap and truncate a string with textwrap in Python
  • Transpose 2D list in Python (swap rows and columns)
  • Generate gradient image with Python, NumPy
  • NumPy: Compare two arrays element-wise
  • Set operations in Python (union, intersection, symmetric difference, etc.)
  • Count elements in a list with collections.Counter in Python
  • Get image size (width, height) with Python, OpenCV, Pillow (PIL)
  • Concatenate images with Python, Pillow

Python Tutorial

File handling, python modules, python numpy, python pandas, python matplotlib, python scipy, machine learning, python mysql, python mongodb, python reference, module reference, python how to, python examples, python operators.

Operators are used to perform operations on variables and values.

In the example below, we use the + operator to add together two values:

Python divides the operators in the following groups:

  • Arithmetic operators
  • Assignment operators
  • Comparison operators
  • Logical operators
  • Identity operators
  • Membership operators
  • Bitwise operators

Python Arithmetic Operators

Arithmetic operators are used with numeric values to perform common mathematical operations:

Operator Name Example Try it
+ Addition x + y
- Subtraction x - y
* Multiplication x * y
/ Division x / y
% Modulus x % y
** Exponentiation x ** y
// Floor division x // y

Python Assignment Operators

Assignment operators are used to assign values to variables:

Operator Example Same As Try it
= x = 5 x = 5
+= x += 3 x = x + 3
-= x -= 3 x = x - 3
*= x *= 3 x = x * 3
/= x /= 3 x = x / 3
%= x %= 3 x = x % 3
//= x //= 3 x = x // 3
**= x **= 3 x = x ** 3
&= x &= 3 x = x & 3
|= x |= 3 x = x | 3
^= x ^= 3 x = x ^ 3
>>= x >>= 3 x = x >> 3
<<= x <<= 3 x = x << 3
:= print(x := 3) x = 3
print(x)

Advertisement

Python Comparison Operators

Comparison operators are used to compare two values:

Operator Name Example Try it
== Equal x == y
!= Not equal x != y
> Greater than x > y
< Less than x < y
>= Greater than or equal to x >= y
<= Less than or equal to x <= y

Python Logical Operators

Logical operators are used to combine conditional statements:

Operator Description Example Try it
and  Returns True if both statements are true x < 5 and  x < 10
or Returns True if one of the statements is true x < 5 or x < 4
not Reverse the result, returns False if the result is true not(x < 5 and x < 10)

Python Identity Operators

Identity operators are used to compare the objects, not if they are equal, but if they are actually the same object, with the same memory location:

Operator Description Example Try it
is  Returns True if both variables are the same object x is y
is not Returns True if both variables are not the same object x is not y

Python Membership Operators

Membership operators are used to test if a sequence is presented in an object:

Operator Description Example Try it
in  Returns True if a sequence with the specified value is present in the object x in y
not in Returns True if a sequence with the specified value is not present in the object x not in y

Python Bitwise Operators

Bitwise operators are used to compare (binary) numbers:

Operator Name Description Example Try it
AND Sets each bit to 1 if both bits are 1 x & y
| OR Sets each bit to 1 if one of two bits is 1 x | y
^ XOR Sets each bit to 1 if only one of two bits is 1 x ^ y
~ NOT Inverts all the bits ~x
<< Zero fill left shift Shift left by pushing zeros in from the right and let the leftmost bits fall off x << 2
>> Signed right shift Shift right by pushing copies of the leftmost bit in from the left, and let the rightmost bits fall off x >> 2

Operator Precedence

Operator precedence describes the order in which operations are performed.

Parentheses has the highest precedence, meaning that expressions inside parentheses must be evaluated first:

Multiplication * has higher precedence than addition + , and therefor multiplications are evaluated before additions:

The precedence order is described in the table below, starting with the highest precedence at the top:

Operator Description Try it
Parentheses
Exponentiation
    Unary plus, unary minus, and bitwise NOT
      Multiplication, division, floor division, and modulus
  Addition and subtraction
  Bitwise left and right shifts
Bitwise AND
Bitwise XOR
Bitwise OR
                    Comparisons, identity, and membership operators
Logical NOT
AND
OR

If two operators have the same precedence, the expression is evaluated from left to right.

Addition + and subtraction - has the same precedence, and therefor we evaluate the expression from left to right:

Get Certified

COLOR PICKER

colorpicker

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: [email protected]

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail: [email protected]

Top Tutorials

Top references, top examples, get certified.

Python Playbooks Logo

Operators in Python (arithmetic, comparison, etc.)

Operators are symbols that perform operations on values in a programming language. In Python, there are several types of operators, including arithmetic, comparison, assignment, logical, and bitwise operators. Understanding these operators and how to use them is a crucial aspect of programming in Python.

Arithmetic operators perform mathematical operations on values. The most commonly used arithmetic operators in Python are + (addition), – (subtraction), * (multiplication), / (division), % (modulus), and ** (exponentiation). For example:

In this example, the variables x , y , and z are assigned the values 10 , 5 , and the result of various arithmetic operations, respectively. The + operator adds two values, the – operator subtracts one value from another, the * operator multiplies two values, the / operator divides one value by another, the % operator returns the remainder after division, and the ** operator raises one value to the power of another.

Comparison operators compare two values and return a Boolean value (True or False) based on the comparison. The most commonly used comparison operators in Python are == (equal to), != (not equal to), > (greater than), < (less than), >= (greater than or equal to), and <= (less than or equal to). For example:

In this example, the variables x , y , and z are assigned the values 10 , 5 , and the result of various comparison operations, respectively. The == operator returns True if two values are equal and False otherwise, the != operator returns True if two values are not equal and False otherwise, the > operator returns True if one value is greater than another and False otherwise, the < operator returns True if one value is less than another and False otherwise, the >= operator returns True if one value is greater than or equal to another and False otherwise, and the <= operator returns True if one value is less than or equal to another and False otherwise.

Assignment operators assign values to variables. The most commonly used assignment operator in Python is = (equal to). For example:

In this example, the variable x is assigned the value 10 , the variable y is assigned the value 5 , and the variable z is assigned the value of x ( 10 ).

Logical operators perform logical operations on Boolean values. The most commonly used logical operators in Python are and, or, and not. For example:

In this example, the variables x , y , and z are assigned the values True , `False

site logo2

Arithmetic And Assignment Operators In Python

  • Post author: Maitry
  • Post category: Quick References
  • Post comments: 0 Comments

Hello Pythonistas, here’s a quick reference to arithmetic and assignment operators in Python.

Operators In Python

Operators are simple  symbols  or  keywords (reserved by python) that perform some task between two given values.

These  values  can be string, integer, float, or any data type and even variable.

See simple😇, isn’t it? Let’s in detail find out about all of its 6 types.

Types of operators arithmetic and assignment

Arithmetic Operators

These operators perform mathematical tasks on the two values(operand), like +,-,/,*, etc. Let’s see each one of them in detail.

OPERATORNAMEEXAMPLEEXPLANATION
+Addition adds two numbers
Subtraction performs subtraction
*Multiplication multiplies two numbers
/Division divides one number with the other
//Floor Division gives the answer in   after dividing
%Modulus gives the remainder after dividing
**Exponentiation raises first to the power of second

Assignment Operators

Has your teacher👩‍🏫 ever assigned you homework?

She might have assigned it to you using blackboard and chalk.

Assignment operators assign values to variables, they work similar to chalk and blackboard, that is, act as a tool for assignment.

For example, a = 10 here, '=' is an assignment operator it gives the variable 'a' which is on the left the value '10' which is on right.

Let’s look at these operators in detail.

OperatorNameExampleTwin toExplanation
=Equals to This is used to to any variable
+=Plus equals to This is used to numbers in a pythonic way.
-=Minus equals to This is used to in a pythonic way.
*=Multiply equals to This is used to in a pythonic way
/=Divide equals to This is used to in a pythonic way
//=Floor division equals to This is used to in a pythonic way
**=Exponentiation equals to This is used to in a pythonic way
%=Modulus equals to This is used to in a pythonic way

Share this:

  • Click to share on Twitter (Opens in new window)
  • Click to share on WhatsApp (Opens in new window)
  • Click to share on LinkedIn (Opens in new window)
  • Click to share on Facebook (Opens in new window)
  • Click to share on Reddit (Opens in new window)

You Might Also Like

Read more about the article How To Ask The User A Question In Python

How To Ask The User A Question In Python

Coding your 1st line of code.

Read more about the article Operator Precedence In Python

Operator Precedence In Python

Read more about the article What Are The Methods Of List In Python With Examples?

What Are The Methods Of List In Python With Examples?

Leave a reply.

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

Python Tutorial

  • Python Basics
  • Python - Home
  • Python - Overview
  • Python - History
  • Python - Features
  • Python vs C++
  • Python - Hello World Program
  • Python - Application Areas
  • Python - Interpreter
  • Python - Environment Setup
  • Python - Virtual Environment
  • Python - Basic Syntax
  • Python - Variables
  • Python - Data Types
  • Python - Type Casting
  • Python - Unicode System
  • Python - Literals
  • Python - Operators
  • Python - Arithmetic Operators
  • Python - Comparison Operators

Python - Assignment Operators

  • Python - Logical Operators
  • Python - Bitwise Operators
  • Python - Membership Operators
  • Python - Identity Operators
  • Python - Operator Precedence
  • Python - Comments
  • Python - User Input
  • Python - Numbers
  • Python - Booleans
  • Python Control Statements
  • Python - Control Flow
  • Python - Decision Making
  • Python - If Statement
  • Python - If else
  • Python - Nested If
  • Python - Match-Case Statement
  • Python - Loops
  • Python - for Loops
  • Python - for-else Loops
  • Python - While Loops
  • Python - break Statement
  • Python - continue Statement
  • Python - pass Statement
  • Python - Nested Loops
  • Python Functions & Modules
  • Python - Functions
  • Python - Default Arguments
  • Python - Keyword Arguments
  • Python - Keyword-Only Arguments
  • Python - Positional Arguments
  • Python - Positional-Only Arguments
  • Python - Arbitrary Arguments
  • Python - Variables Scope
  • Python - Function Annotations
  • Python - Modules
  • Python - Built in Functions
  • Python Strings
  • Python - Strings
  • Python - Slicing Strings
  • Python - Modify Strings
  • Python - String Concatenation
  • Python - String Formatting
  • Python - Escape Characters
  • Python - String Methods
  • Python - String Exercises
  • Python Lists
  • Python - Lists
  • Python - Access List Items
  • Python - Change List Items
  • Python - Add List Items
  • Python - Remove List Items
  • Python - Loop Lists
  • Python - List Comprehension
  • Python - Sort Lists
  • Python - Copy Lists
  • Python - Join Lists
  • Python - List Methods
  • Python - List Exercises
  • Python Tuples
  • Python - Tuples
  • Python - Access Tuple Items
  • Python - Update Tuples
  • Python - Unpack Tuples
  • Python - Loop Tuples
  • Python - Join Tuples
  • Python - Tuple Methods
  • Python - Tuple Exercises
  • Python Sets
  • Python - Sets
  • Python - Access Set Items
  • Python - Add Set Items
  • Python - Remove Set Items
  • Python - Loop Sets
  • Python - Join Sets
  • Python - Copy Sets
  • Python - Set Operators
  • Python - Set Methods
  • Python - Set Exercises
  • Python Dictionaries
  • Python - Dictionaries
  • Python - Access Dictionary Items
  • Python - Change Dictionary Items
  • Python - Add Dictionary Items
  • Python - Remove Dictionary Items
  • Python - Dictionary View Objects
  • Python - Loop Dictionaries
  • Python - Copy Dictionaries
  • Python - Nested Dictionaries
  • Python - Dictionary Methods
  • Python - Dictionary Exercises
  • Python Arrays
  • Python - Arrays
  • Python - Access Array Items
  • Python - Add Array Items
  • Python - Remove Array Items
  • Python - Loop Arrays
  • Python - Copy Arrays
  • Python - Reverse Arrays
  • Python - Sort Arrays
  • Python - Join Arrays
  • Python - Array Methods
  • Python - Array Exercises
  • Python File Handling
  • Python - File Handling
  • Python - Write to File
  • Python - Read Files
  • Python - Renaming and Deleting Files
  • Python - Directories
  • Python - File Methods
  • Python - OS File/Directory Methods
  • Python - OS Path Methods
  • Object Oriented Programming
  • Python - OOPs Concepts
  • Python - Classes & Objects
  • Python - Class Attributes
  • Python - Class Methods
  • Python - Static Methods
  • Python - Constructors
  • Python - Access Modifiers
  • Python - Inheritance
  • Python - Polymorphism
  • Python - Method Overriding
  • Python - Method Overloading
  • Python - Dynamic Binding
  • Python - Dynamic Typing
  • Python - Abstraction
  • Python - Encapsulation
  • Python - Interfaces
  • Python - Packages
  • Python - Inner Classes
  • Python - Anonymous Class and Objects
  • Python - Singleton Class
  • Python - Wrapper Classes
  • Python - Enums
  • Python - Reflection
  • Python Errors & Exceptions
  • Python - Syntax Errors
  • Python - Exceptions
  • Python - try-except Block
  • Python - try-finally Block
  • Python - Raising Exceptions
  • Python - Exception Chaining
  • Python - Nested try Block
  • Python - User-defined Exception
  • Python - Logging
  • Python - Assertions
  • Python - Built-in Exceptions
  • Python Multithreading
  • Python - Multithreading
  • Python - Thread Life Cycle
  • Python - Creating a Thread
  • Python - Starting a Thread
  • Python - Joining Threads
  • Python - Naming Thread
  • Python - Thread Scheduling
  • Python - Thread Pools
  • Python - Main Thread
  • Python - Thread Priority
  • Python - Daemon Threads
  • Python - Synchronizing Threads
  • Python Synchronization
  • Python - Inter-thread Communication
  • Python - Thread Deadlock
  • Python - Interrupting a Thread
  • Python Networking
  • Python - Networking
  • Python - Socket Programming
  • Python - URL Processing
  • Python - Generics
  • Python Libraries
  • NumPy Tutorial
  • Pandas Tutorial
  • SciPy Tutorial
  • Matplotlib Tutorial
  • Django Tutorial
  • OpenCV Tutorial
  • Python Miscellenous
  • Python - Date & Time
  • Python - Maths
  • Python - Iterators
  • Python - Generators
  • Python - Closures
  • Python - Decorators
  • Python - Recursion
  • Python - Reg Expressions
  • Python - PIP
  • Python - Database Access
  • Python - Weak References
  • Python - Serialization
  • Python - Templating
  • Python - Output Formatting
  • Python - Performance Measurement
  • Python - Data Compression
  • Python - CGI Programming
  • Python - XML Processing
  • Python - GUI Programming
  • Python - Command-Line Arguments
  • Python - Docstrings
  • Python - JSON
  • Python - Sending Email
  • Python - Further Extensions
  • Python - Tools/Utilities
  • Python - GUIs
  • Python Advanced Concepts
  • Python - Abstract Base Classes
  • Python - Custom Exceptions
  • Python - Higher Order Functions
  • Python - Object Internals
  • Python - Memory Management
  • Python - Metaclasses
  • Python - Metaprogramming with Metaclasses
  • Python - Mocking and Stubbing
  • Python - Monkey Patching
  • Python - Signal Handling
  • Python - Type Hints
  • Python - Automation Tutorial
  • Python - Humanize Package
  • Python - Context Managers
  • Python - Coroutines
  • Python - Descriptors
  • Python - Diagnosing and Fixing Memory Leaks
  • Python - Immutable Data Structures
  • Python Useful Resources
  • Python - Questions & Answers
  • Python - Online Quiz
  • Python - Quick Guide
  • Python - Projects
  • Python - Useful Resources
  • Python - Discussion
  • Python Compiler
  • NumPy Compiler
  • Matplotlib Compiler
  • SciPy Compiler
  • Python - Programming Examples
  • Selected Reading
  • UPSC IAS Exams Notes
  • Developer's Best Practices
  • Questions and Answers
  • Effective Resume Writing
  • HR Interview Questions
  • Computer Glossary

Python Assignment Operator

The = (equal to) symbol is defined as assignment operator in Python. The value of Python expression on its right is assigned to a single variable on its left. The = symbol as in programming in general (and Python in particular) should not be confused with its usage in Mathematics, where it states that the expressions on the either side of the symbol are equal.

Example of Assignment Operator in Python

Consider following Python statements −

At the first instance, at least for somebody new to programming but who knows maths, the statement "a=a+b" looks strange. How could a be equal to "a+b"? However, it needs to be reemphasized that the = symbol is an assignment operator here and not used to show the equality of LHS and RHS.

Because it is an assignment, the expression on right evaluates to 15, the value is assigned to a.

In the statement "a+=b", the two operators "+" and "=" can be combined in a "+=" operator. It is called as add and assign operator. In a single statement, it performs addition of two operands "a" and "b", and result is assigned to operand on left, i.e., "a".

Augmented Assignment Operators in Python

In addition to the simple assignment operator, Python provides few more assignment operators for advanced use. They are called cumulative or augmented assignment operators. In this chapter, we shall learn to use augmented assignment operators defined in Python.

Python has the augmented assignment operators for all arithmetic and comparison operators.

Python augmented assignment operators combines addition and assignment in one statement. Since Python supports mixed arithmetic, the two operands may be of different types. However, the type of left operand changes to the operand of on right, if it is wider.

The += operator is an augmented operator. It is also called cumulative addition operator, as it adds "b" in "a" and assigns the result back to a variable.

The following are the augmented assignment operators in Python:

  • Augmented Addition Operator
  • Augmented Subtraction Operator
  • Augmented Multiplication Operator
  • Augmented Division Operator
  • Augmented Modulus Operator
  • Augmented Exponent Operator
  • Augmented Floor division Operator

Augmented Addition Operator (+=)

Following examples will help in understanding how the "+=" operator works −

It will produce the following output −

Augmented Subtraction Operator (-=)

Use -= symbol to perform subtract and assign operations in a single statement. The "a-=b" statement performs "a=a-b" assignment. Operands may be of any number type. Python performs implicit type casting on the object which is narrower in size.

Augmented Multiplication Operator (*=)

The "*=" operator works on similar principle. "a*=b" performs multiply and assign operations, and is equivalent to "a=a*b". In case of augmented multiplication of two complex numbers, the rule of multiplication as discussed in the previous chapter is applicable.

Augmented Division Operator (/=)

The combination symbol "/=" acts as divide and assignment operator, hence "a/=b" is equivalent to "a=a/b". The division operation of int or float operands is float. Division of two complex numbers returns a complex number. Given below are examples of augmented division operator.

Augmented Modulus Operator (%=)

To perform modulus and assignment operation in a single statement, use the %= operator. Like the mod operator, its augmented version also is not supported for complex number.

Augmented Exponent Operator (**=)

The "**=" operator results in computation of "a" raised to "b", and assigning the value back to "a". Given below are some examples −

Augmented Floor division Operator (//=)

For performing floor division and assignment in a single statement, use the "//=" operator. "a//=b" is equivalent to "a=a//b". This operator cannot be used with complex numbers.

Python Programming

Python Operators

Updated on:  November 14, 2021 | 33 Comments

Learning the operators is an excellent place to start to learn Python. Operators are special symbols that perform specific operations on one or more operands (values) and then return a result. For example, you can calculate the sum of two numbers using an addition ( + ) operator.

The following image shows operator and operands

Python operator and operands

  • Python If-else and Loops Exercise
  • Python Operators and Expression Quiz

Python has seven types of operators that we can use to perform different operation and produce a result.

Arithmetic operator

  • Relational operators

Assignment operators

Logical operators, membership operators, identity operators.

  • Bitwise operators

Table of contents

Addition operator +.

  • Subtraction –

Multiplication *

Floor division //, exponent **, relational (comparison) operators, and (logical and), or (logical or), not (logical not), in operator, not in operator, is operator, is not operator, bitwise and &, bitwise or |, bitwise xor ^.

  • Bitwise 1’s complement ~
  • Bitwise left-shift <<
  • Bitwise right-shift >>

Python Operators Precedence

Arithmetic operators are the most commonly used. The Python programming language provides arithmetic operators that perform addition, subtraction, multiplication, and division. It works the same as basic mathematics.

There are seven arithmetic operators we can use to perform different mathematical operations, such as:

  • + (Addition)
  • - (Subtraction)
  • * (Multiplication)
  • / (Division)
  • // Floor division)
  • ℅ (Modulus)
  • ** (Exponentiation)

Now, let’s see how to use each arithmetic operator in our program with the help of examples.

It adds two or more operands and gives their sum as a result. It works the same as a unary plus. In simple terms,  It performs the addition of two or more than two values and gives their sum as a result.

Also, we can use the addition operator with strings, and it will become string concatenation.

Subtraction -

Use to subtracts the second value from the first value and gives the difference between them. It works the same as a unary minus. The subtraction operator is denoted by - symbol.

Multiply two operands. In simple terms, it is used to multiplies two or more values and gives their product as a result. The multiplication operator is denoted by a * symbol.

You can also use the multiplication operator with string. When used with string, it works as a repetition.

Divide the left operand (dividend) by the right one (divisor) and provide the result (quotient ) in a float value. The division operator is denoted by a / symbol.

  • The division operator performs floating-point arithmetic. Hence it always returns a float value.
  • Don’t divide any number by zero. You will get a Zero Division Error: Division by zero

Floor division returns the quotient (the result of division) in which the digits after the decimal point are removed. In simple terms, It is used to divide one value by a second value and gives a quotient as a round figure value to the next smallest whole value.

It works the same as a division operator, except it returns a possible integer. The // symbol denotes a floor division operator.

  • Floor division can perform both floating-point and integer arithmetic.
  • If both operands are int type, then the result types. If at least one operand type, then the result is a float type.

The remainder of the division of left operand by the right. The modulus operator is denoted by a % symbol. In simple terms, the Modulus operator divides one value by a second and gives the remainder as a result.

Using exponent operator left operand raised to the power of right. The exponentiation operator is denoted by a double asterisk ** symbol. You can use it as a shortcut to calculate the exponential value.

For example, 2**3 Here 2 is multiplied by itself 3 times, i.e., 2*2*2 . Here the 2 is the base, and 3 is an exponent.

Relational operators are also called comparison operators. It performs a comparison between two values. It returns a boolean  True or False depending upon the result of the comparison.

Python has the following six relational operators.

Assume variable x holds 10 and variable y holds 5

Example
 (Greater than)It returns True if the left operand is greater than the right  
result is 
 (Less than)It returns True if the left operand is less than the right  
result is 
 (Equal to)It returns True if both operands are equal  
result is 
 (Not equal to)It returns True if both operands are equal  
result is 
 (Greater than or equal to)It returns True if the left operand is greater than or equal to the right  
result is 
 (Less than or equal to)It returns True if the left operand is less than or equal to the right  
result is 

You can compare more than two values also. Assume variable x holds 10, variable y holds 5, and variable z holds 2.

So print(x > y > z) will return True because x is greater than y, and y is greater than z, so it makes x is greater than z.

In Python, Assignment operators are used to assigning value to the variable. Assign operator is denoted by = symbol. For example, name = "Jessa" here, we have assigned the string literal ‘Jessa’ to a variable name.

Also, there are shorthand assignment operators in Python. For example, a+=2 which is equivalent to a = a+2 .

 (Assign) Assign 5 to variable  a = 5
 (Add and assign) Add 5 to a and assign it as a new value to  a = a+5
 (Subtract and assign) Subtract 5 from variable   and assign it as a new value to  a = a-5
 (Multiply and assign) Multiply variable   by 5 and assign it as a new value to  a = a*5
 (Divide and assign) Divide variable   by 5 and assign a new value to  a = a/5
 (Modulus and assign) Performs modulus on two values and assigns it as a new value to  a = a%5
 (Exponentiation and assign) Multiply   five times and assigns the result to  a = a**5
 (Floor-divide and assign) Floor-divide   by 5 and assigns the result to  a = a//5

Logical operators are useful when checking a condition is true or not. Python has three logical operators. All logical operator returns a boolean value True or False depending on the condition in which it is used.

 (Logical and)True if both the operands are Truea and b
 (Logical or)True if either of the operands is Truea or b
 (Logical not)True if the operand is Falsenot a

The logical and operator returns True if both expressions are True. Otherwise, it will return. False .

In the case of arithmetic values , Logical and always returns the second value ; as a result, see the following example.

The  logical or the operator returns a boolean  True if one expression is true, and it returns False if both values are false .

In the case of arithmetic values , Logical or it always returns the first value; as a result, see the following code.

The  logical not operator returns boolean True if the expression is false .

In the case of arithmetic values , Logical not always return False for nonzero value.

Python’s membership operators are used to check for membership of objects in sequence, such as string, list , tuple . It checks whether the given value or variable is present in a given sequence. If present, it will return True else False .

In Python, there are two membership operator  in  and  not in

It returns a result as True if it finds a given object in the sequence. Otherwise, it returns False .

Let’s check if the number 15 present in a given list using the in operator.

It returns True if the object is not present in a given sequence. Otherwise, it returns False

Use the Identity operator to check whether the value of two variables is the same or not. This operator is known as a reference-quality operator because the identity operator compares values according to two variables’ memory addresses.

Python has 2 identity operators is and is not .

The is operator returns Boolean True or False . It Return True if the memory address first value is equal to the second value. Otherwise, it returns False .

Here, we can use is() function to check whether both variables are pointing to the same object or not.

The is not the operator returns boolean values either True or False . It Return True if the first value is not equal to the second value. Otherwise, it returns False .

Bitwise Operators

In Python, bitwise operators are used to performing bitwise operations on integers. To perform bitwise, we first need to convert integer value to binary (0 and 1) value.

The bitwise operator operates on values bit by bit, so it’s called bitwise . It always returns the result in decimal format. Python has 6 bitwise operators listed below.

  • & Bitwise and
  • | Bitwise or
  • ^ Bitwise xor
  • ~ Bitwise 1’s complement
  • << Bitwise left-shift
  • >>  Bitwise right-shift

It performs  logical AND  operation on the integer value after converting an integer to a binary value and gives the result as a decimal value. It returns True only if both operands are True. Otherwise, it returns False .

Here, every integer value is converted into a binary value. For example, a =7 , its binary value is 0111, and b=4 , its binary value is 0100. Next we performed logical AND, and got 0100 as a result, similarly for a and c, b and c

Following diagram shows AND operator evaluation.

Python bitwise AND

It performs  logical OR  operation on the integer value after converting integer value to binary value and gives the result a decimal value. It returns  False  only if both operands are  True . Otherwise, it returns  True .

Here, every integer value is converted into binary. For example,  a =7 its binary value is 0111, and b=4 , its binary value is 0100, after logical OR, we got 0111 as a result. Similarly for  a  and  c ,  b and  c .

Python bitwise OR

It performs Logical XOR  ^  operation on the binary value of a integer and gives the result as a decimal value.

Example : –

Here, again every integer value is converted into binary. For example,  a =7  its binary value is 0111 and b=4 , and its binary value is 0100, after logical XOR we got 0011 as a result. Similarly for  a  and  c ,  b  and  c .

Python bitwise XOR

Bitwise 1’s complement  ~

It performs 1’s complement operation. It invert each bit of binary value and returns the bitwise negation of a value as a result.

Bitwise left-shift  <<

The left-shift  <<  operator performs a shifting bit of value by a given number of the place and fills 0’s to new positions.

Python bitwise left shift

Bitwise right-shift  >>

The left-shift  >>  operator performs shifting a bit of value to the right by a given number of places. Here some bits are lost.

Python bitwise right shift

In Python, operator precedence and associativity play an essential role in solving the expression. An expression is the combination of variables and operators that evaluate based on operator precedence.

We must know what the precedence (priority) of that operator is and how they will evaluate down to a single value. Operator precedence is used in an expression to determine which operation to perform first.

In the above example. 1st precedence goes to a parenthesis () , then for plus and minus operators. The expression will be executed as.

The following tables shows operator precedence highest to lowest.

1 (Highest) Parenthesis
2 Exponent
3 , , Unary plus, Unary Minus, Bitwise negation
4 , , , Multiplication, Division, Floor division, Modulus
5 , Addition, Subtraction
6 , Bitwise shift operator
7 Bitwise AND
8 Bitwise XOR
9 Bitwise OR
10 , , , , , Comparison
11 , , ,  Identity, Membership
12notLogical NOT
13andLogical AND
14 (Lowest)orLogical OR

Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.

About Vishal

arithmetic assignment operator in python

I’m  Vishal Hule , the Founder of PYnative.com. As a Python developer, I enjoy assisting students, developers, and learners. Follow me on  Twitter .

Related Tutorial Topics:

Python exercises and quizzes.

Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.

  • 15+ Topic-specific Exercises and Quizzes
  • Each Exercise contains 10 questions
  • Each Quiz contains 12-15 MCQ

Loading comments... Please wait.

About PYnative

PYnative.com is for Python lovers. Here, You can get Tutorials, Exercises, and Quizzes to practice and improve your Python skills .

Explore Python

  • Learn Python
  • Python Basics
  • Python Databases
  • Python Exercises
  • Python Quizzes
  • Online Python Code Editor
  • Python Tricks

To get New Python Tutorials, Exercises, and Quizzes

Legal Stuff

We use cookies to improve your experience. While using PYnative, you agree to have read and accepted our Terms Of Use , Cookie Policy , and Privacy Policy .

Copyright © 2018–2024 pynative.com

Python Assignment Operators

Lesson Contents

Python assignment operators are one of the operator types and assign values to variables . We use arithmetic operators here in combination with a variable.

Let’s take a look at some examples.

Operator Assignment (=)

This is the most basic assignment operator and we used it before in the lessons about lists , tuples , and dictionaries .  For example, we can assign a value (integer) to a variable:

Operator Addition (+=)

We can add a number to our variable like this:

Using the above operator is the same as doing this:

The += operator is shorter to write but the end result is the same.

Operator Subtraction (-=)

We can also subtract a value. For example:

Using this operator is the same as doing this:

Operator Multiplication (*=)

We can also use multiplication. We’ll multiply our variable by 4:

Which is similar to:

Operator Division (/=)

Let’s try the divide operator:

This is the same as:

Operator Modulus (%=)

We can also calculate the modulus. How about this:

This is the same as doing it like this:

Operator Exponentiation (**=)

How about exponentiation? Let’s give it a try:

Which is the same as doing it like this:

Operator Floor Division (//=)

The last one, floor division:

You have now learned how to use the Python assignment operators to assign values to variables and how you can use them with arithmetic operators . I hope you enjoyed this lesson. If you have any questions, please leave a comment.

Ask a question or start a discussion by visiting our Community Forum

  • 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

Python Operators Explained in Detail with Examples

January 9, 2024

When diving into the world of Python programming, understanding Python operators is akin to learning the alphabets of a new language. These operators act as the building blocks for any Python script, playing a critical role in carrying out operations like arithmetic calculations, comparisons, and logical decisions. Not only do they facilitate code execution, but they also make your code more efficient and readable. In this comprehensive guide, we will explore various types of Python operators, how they function, and why they are essential for anyone aspiring to master Python programming.

Different Python Operators

Here are the list of Python Operators:

  • Arithmetic Operators
  • Comparison Operators
  • Logical Operators
  • Assignment Operators
  • Augmented Operators
  • Bitwise Operators
  • Identity Operators
  • Membership Operators

We will cover these in detail in next chapters.

1. Arithmetic operators in Python

As the name suggests, these operators perform various arithmetic operations and calculations like addition, multiplications, division, etc. They can be used with numerical data types like integers and floats, and some can even be used with strings and lists for operations like concatenation and repetition.

Below is a table that provides a detailed explanation of arithmetic operators in Python.

Operator Description Example Output
Addition
Subtraction
Multiplication
Division
Modulus
Exponentiation
Floor Division

In each example, the variable a is used to store the result of the operation, and then print(a) is used to display the output.

2. Comparison operators in Python

Comparison operators are also known as rational operators as well. They are used to compare different values.  They evaluate different types of expressions and manipulate the values of variables by performing different operations on them.

Operator Description Python Code Example Output
Checks if the values on either side of the operator are equal, and returns if they are.
Checks if the values on either side of the operator are not equal, and returns if they aren't.
Checks if the left-hand operand is greater than the right-hand operand, and returns if it is.
Checks if the left-hand operand is less than the right-hand operand, and returns if it is.
Checks if the left-hand operand is greater than or equal to the right-hand operand.
Checks if the left-hand operand is less than or equal to the right-hand operand.

In each code example, the variable a is used to store the result of the comparison operation, and then print(a) is used to display the Boolean output ( True or False ).

3. Logical operators in Python

Python logical operators are used to evaluate the one or more than one condition between variables or operands by providing specific results. i.e True and False . Useful for making decisions in code (conditionals) and testing multiple conditions . It can be used with any data types that can be converted to Boolean values.

Operator Description Python Code Example Output
Evaluates to if both the left-hand and right-hand expressions are true. Otherwise, returns .
Evaluates to if at least one of the left-hand or right-hand expressions is true. Otherwise, returns .
Reverses the Boolean value of the expression it precedes. If the expression is , makes it .

In each example, the variable a is used to store the result of the logical operation, and print(a) is used to display the resulting Boolean value ( True or False ).

4. Assignment Operators

Assignment operators are primarily used to assign values to variables. They perform a single function of assigning a value from the right-hand side to the variable on the left-hand side. It is useful for initializing variables and updating their values.

Below is a table that explains the assignment operators in Python, along with code examples using a small variable name ( a ) and the print() statement to display the result.

Operator Description Python Code Example Output
Assigns the value on the right to the variable on the left.
Adds the right-hand operand to the left-hand operand and assigns the result to the left-hand operand.
Subtracts the right-hand operand from the left-hand operand and assigns the result to the left-hand operand.
Multiplies the right-hand operand by the left-hand operand and assigns the result to the left-hand operand.
Divides the left-hand operand by the right-hand operand and assigns the result to the left-hand operand.
Takes the modulus of the left-hand operand by the right-hand operand and assigns the result to the left-hand operand.
Raises the left-hand operand to the power of the right-hand operand and assigns the result to the left-hand operand.
Performs floor division on the left-hand operand by the right-hand operand and assigns the result to the left-hand operand.

In each example, the variable a is initially assigned a value. Then, an assignment operator modifies this value, and print(a) displays the updated value.

5. Augmented Operators (Compound Assignment Operators)

Python has a set of operators known as "augmented assignment operators," also sometimes called "compound assignment operators." These operators provide a shorthand way to apply an operation and an assignment in a single step. They are similar to assignment operators but perform an additional operation before the assignment.

Unlike normal assignment operators, Augmented Assignment Operators are used to replace those statements where a binary operator takes two operands, variable1 and variable1 and then assigns a final result back to one of the operands.

Below is a table that outlines the augmented assignment operators in Python, complete with code examples using a small variable name ( a ) and the print() function to display the result.

Operator Description Python Code Example Output
Adds the right-hand operand to the left-hand operand and assigns the result to the left-hand operand.
Subtracts the right-hand operand from the left-hand operand and assigns the result to the left-hand operand.
Multiplies the right-hand operand by the left-hand operand and assigns the result to the left-hand operand.
Divides the left-hand operand by the right-hand operand and assigns the result to the left-hand operand.
Takes the modulus of the left-hand operand by the right-hand operand and assigns the result to the left-hand operand.
Raises the left-hand operand to the power of the right-hand operand and assigns the result to the left-hand operand.
Performs floor division on the left-hand operand by the right-hand operand and assigns the result to the left-hand operand.
Performs bitwise AND on both operands and assigns the result to the left-hand operand.
Performs bitwise OR on both operands and assigns the result to the left-hand operand.
Performs bitwise XOR on both operands and assigns the result to the left-hand operand.
Left shifts the bits of the left-hand operand by the right-hand operand and assigns the result to the left-hand operand.
Right shifts the bits of the left-hand operand by the right-hand operand and assigns the result to the left-hand operand.

In each example, the variable a is initially assigned a value. Then, an augmented assignment operator modifies this value, and print(a) displays the updated value.

6. Bitwise Operators

Bitwise operators in Python are used to operate at a binary level. This means they look directly at the binary digits or binary bits of an integer. Below is a table that explains each bitwise operator in Python, along with a code example that uses a small variable name ( a ) and the print() statement to display the result.

Operator Description Python Code Example Output
Bitwise AND: Sets each bit to 1 if both bits are 1.
` ` Bitwise OR: Sets each bit to 1 if one of two bits is 1. `a = 5
Bitwise XOR: Sets each bit to 1 if only one of two bits is 1.
Bitwise NOT: Inverts all the bits.
Left Shift: Shifts the bits of the number to the left by the specified number of positions.
Right Shift: Shifts the bits of the number to the right by the specified number of positions.

Below are some examples to help you understand how these operators work in Python:

Bitwise AND ( & ): This operator compares each binary digit of the first operand to the corresponding binary digit of the second operand. If both digits are 1 , the digit in the resulting binary representation is 1 , otherwise 0 .

Bitwise OR ( | ):  This operator also compares each binary digit of the first operand to the corresponding binary digit of the second operand. If either of the digits is 1 , the resulting binary digit is 1 .

Bitwise XOR ( ^ ):  The XOR operator compares each bit of its first operand to the corresponding bit of its second operand. If one bit is 0 and the other bit is 1 , the corresponding result bit is set to 1 .

Bitwise NOT ( ~ ):  This operator is a unary operator, meaning it works with a single operand. Bitwise NOT will invert the number's bit-wise representation. Note that because Python uses signed integers , the result will be the two's complement of the inverted bits.

Left Shift ( << ):  The left shift operator shifts the bits of a number to the left by a specified number of positions. Each left shift doubles the number, as it is equivalent to multiplication by 2 to the power of the number of shifted positions.

Right Shift ( >> ):  The right shift operator shifts the bits of a number to the right by a specified number of positions. Each right shift halves the number, rounding down.

7. Identity Operators

Identity operators in Python are used to compare the memory locations of two objects. They help to check if two variables refer to the same object in memory. Below is a table that describes the identity operators, accompanied by Python code examples using small variable names ( a and b ) and the print() function to display the result.

Operator Description Python Code Example Output
Evaluates to if the variables on either side of the operator point to the same object.
Evaluates to if the variables on either side of the operator do not point to the same object.

Description and Use-cases

is Operator : The is operator checks whether both the operands refer to the same object (i.e., point to the same memory location). It's often used to test if a variable is None , although it can also be used for other objects like lists or dictionaries to ensure that two variables point to the same data structure.

is not Operator : The is not operator is essentially the opposite of the is operator. It checks whether two variables refer to different objects in memory. This is useful for ensuring that two variables don't share the same underlying data.

Remember, is and is not operators should not be confused with == and != operators. The former compare the memory locations, whereas the latter compare the values.

8. Membership Operators

Membership operators are used to test whether a value is a member of a sequence such as a list, tuple, or string, or a collection like a dictionary . Below is a table explaining the membership operators in Python, with code examples using small variable names ( a and b ) and the print() statement to display the result.

Operator Description Python Code Example Output
Checks if the specified element exists within the sequence or collection.
Checks if the specified element does not exist within the sequence or collection.

in Operator : The in operator is used to check if a value exists in a sequence or a collection. It's a quick way to check for the presence of a specific item.

not in Operator : The not in operator is essentially the opposite of the in operator. It checks if a specified element is not present in a given sequence or collection.

Assignment Vs Augmented Assignment Operators

The fundamental difference between assignment operators and augmented assignment operators lies in their functionality and readability.

Assignment Operators:

Basic Function : Assignment operators are mainly used to assign values to variables.

Single Operation : Assignment operators perform just one function: they assign the value on the right-hand side to the variable on the left-hand side.

Multiple Steps for Operations : If you need to perform an operation (like addition, subtraction, etc.) and then assign the result to the variable, you have to do it in multiple steps or lines.

Augmented Assignment Operators:

Enhanced Function : Augmented assignment operators perform an operation in addition to assignment, effectively combining the two into a single action.

Conciseness : They allow for more concise code. Instead of writing a = a + 2 , you can simply write a += 2 .

Efficiency : Augmented assignment operators may be more efficient in some cases, as they can reduce the amount of typing and potentially perform the operation faster, although the speed difference is generally negligible for basic types.

Multiple Operations : They make it easier to perform complex calculations and reassignments in a single step.

Operators precedence order in Python

Operator precedence in Python determines the order in which operators are evaluated when multiple operators are present in an expression. Operators with higher precedence are evaluated before operators with lower precedence.

Here is a list of operators in Python , sorted from highest precedence to lowest:

  • Parentheses () : Expressions inside parentheses are evaluated first.
  • Exponentiation ** : Right-to-left associativity.
  • Complement, Unary Plus and Minus ~ + - : Unary operators.
  • Multiply, Divide, Floor Divide, and Modulus * / // % : Left-to-right associativity.
  • Addition and Subtraction + - : Left-to-right associativity.
  • Bitwise Right Shift and Left Shift >> << : Left-to-right associativity.
  • Bitwise AND & : Left-to-right associativity.
  • Bitwise XOR ^ : Left-to-right associativity.
  • Bitwise OR | : Left-to-right associativity.
  • Comparison Operators == != < <= > >= : Left-to-right associativity.
  • Identity Operators is is not : Left-to-right associativity.
  • Membership Operators in not in : Left-to-right associativity.
  • Logical NOT not : Right-to-left associativity.
  • Logical AND and : Left-to-right associativity.
  • Logical OR or : Left-to-right associativity.
  • Conditional Expression if else : Right-to-left associativity.
  • Assignment = : Right-to-left associativity.
  • Augmented Assignment += -= *= /= //= %= **= &= ^= |= <<= >>= : Right-to-left associativity.

When multiple operators have the same precedence, Python usually evaluates them from left to right (left-to-right associativity). The exception to this rule is the exponentiation operator ( ** ), which has right-to-left associativity, meaning that operations are evaluated from right to left.

For example:

  • With the expression 3 + 4 * 2 , the multiplication ( * ) operator has higher precedence than addition ( + ), so 4 * 2 is evaluated first, resulting in 3 + 8 which is 11 .
  • In the expression 2 ** 3 ** 2 , the ** operator is right associative, so 3 ** 2 is evaluated first, resulting in 2 ** 9 which is 512

Special Cases and Syntax

Python allows some operators to be used in unconventional ways. For example, you can use the * operator to repeat strings and lists.

While using operators, you should follow certain syntax rules, like putting them between operands (in infix notation), or ensuring that they are applied to compatible data types.

Chaining : Python allows you to chain multiple comparisons to perform a more complex test.

Chained comparisons also benefit from short-circuit behavior. This means that if one comparison fails, the remaining ones are not executed, which can improve performance.

Mixing Operators in Expressions: Python allows for mixing certain types of operators, but it's important to use parentheses to make the expression clear.

When mixing operators with different data types, Python will usually automatically convert the types to make them compatible, if possible.

Common Mistakes and Best Practices

Importance of parentheses.

Clarifying Ambiguity : Parentheses help in making the expression unambiguous. This is especially crucial when dealing with operators of different precedences.

Parentheses can also make complex expressions more readable, even if they're not strictly necessary.

Floating-Point Arithmetic Caveats

Precision : Floating-point numbers do not always represent decimal numbers precisely, which can lead to errors in calculations.

Integer Division : When dividing integers, use // for integer division and / for floating-point division to avoid unexpected results.

Common Pitfalls with Assignment Operators

Immutable Reassignment : Be cautious when you are working with immutable types like tuples or strings. Reassignment will produce a new object instead of modifying the original one.

Augmented Assignment : Remember that augmented assignment ( += , *= etc.) can behave differently for mutable and immutable objects.

Chaining Assignments : While Python allows for chained assignments like a = b = 1 , be cautious when using this feature with mutable objects as it can lead to unexpected behavior.

Practical Examples

How to use Arithmetic Operators in Math Calculations

Arithmetic operators come in handy for a wide range of math calculations. Here we are calculating Area and Perimeter:

Using Comparison Operators in Conditional Statements

Comparison operators are frequently used in conditional statements like if , elif , and else . Here we are determining the Largest Number:

Using Logical Operators in Decision Making

Logical operators can be used for making complex decisions. Here we are checking the eligibility for a Loan:

Real-world Scenarios where Bitwise Operators are Useful

Bitwise operators are particularly useful in low-level programming and bit manipulation:

Setting Flags

Checking Flags

How Membership and Identity Operators Work in Data Structures like Lists, Sets, and Dictionaries

Membership and identity operators are quite useful when working with data structures:

Dictionaries

Python has seven different types of operators. Arithmetic operators, logic operators, assignment operators, augmented operators, bitwise operators, and two special kinds of operators; membership operator and identity operator. In this tutorial, we learned about each type of these operators by taking different examples.  Moreover, we also covered the precedence of these operators over each other.

Further Reading

Python operators Augmented operators More about python operators

Bashir Alam

Bashir Alam

He is a Computer Science graduate from the University of Central Asia, currently employed as a full-time Machine Learning Engineer at uExel. His expertise lies in Python, Java, Machine Learning, OCR, text extraction, data preprocessing, and predictive models. You can connect with him on his LinkedIn profile.

Can't find what you're searching for? Let us assist you.

Enter your query below, and we'll provide instant results tailored to your needs.

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can send mail to [email protected]

Thank You for your support!!

Leave a Comment Cancel reply

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

Notify me via e-mail if anyone answers my comment.

arithmetic assignment operator in python

We try to offer easy-to-follow guides and tips on various topics such as Linux, Cloud Computing, Programming Languages, Ethical Hacking and much more.

Recent Comments

Popular posts, 7 tools to detect memory leaks with examples, 100+ linux commands cheat sheet & examples, tutorial: beginners guide on linux memory management, top 15 tools to monitor disk io performance with examples, overview on different disk types and disk interface types, 6 ssh authentication methods to secure connection (sshd_config), how to check security updates list & perform linux patch management rhel 6/7/8, 8 ways to prevent brute force ssh attacks in linux (centos/rhel 7).

Privacy Policy

HTML Sitemap

  • 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

Augmented Assignment Operators in Python

An assignment operator is an operator that is used to assign some value to a variable. Like normally in Python, we write “ a = 5 “ to assign value 5 to variable ‘a’. Augmented assignment operators have a special role to play in Python programming. It basically combines the functioning of the arithmetic or bitwise operator with the assignment operator. So assume if we need to add 7 to a variable “a” and assign the result back to “a”, then instead of writing normally as “ a = a + 7 “, we can use the augmented assignment operator and write the expression as “ a += 7 “. Here += has combined the functionality of arithmetic addition and assignment.

So, augmented assignment operators provide a short way to perform a binary operation and assigning results back to one of the operands. The way to write an augmented operator is just to write that binary operator and assignment operator together. In Python, we have several different augmented assignment operators like +=, -=, *=, /=, //=, **=, |=, &=, >>=, <<=, %= and ^=. Let’s see their functioning with the help of some exemplar codes:

1. Addition and Assignment (+=): This operator combines the impact of arithmetic addition and assignment. Here,

 a = a + b can be written as a += b

2. Subtraction and Assignment (-=): This operator combines the impact of subtraction and assignment.  

a = a – b can be written as a -= b

Example:  

3. Multiplication and Assignment (*=): This operator combines the functionality of multiplication and assignment.  

a = a * b can be written as a *= b

4. Division and Assignment (/=): This operator has the combined functionality of division and assignment.  

a = a / b can be written as a /= b

5. Floor Division and Assignment (//=): It performs the functioning of floor division and assignment.  

a = a // b can be written as a //= b

6. Modulo and Assignment (%=): This operator combines the impact of the modulo operator and assignment.  

a = a % b can be written as a %= b

7. Power and Assignment (**=): This operator is equivalent to the power and assignment operator together.  

a = a**b can be written as a **= b

8. Bitwise AND & Assignment (&=): This operator combines the impact of the bitwise AND operator and assignment operator. 

a = a & b can be written as a &= b

9. Bitwise OR and Assignment (|=): This operator combines the impact of Bitwise OR and assignment operator.  

a = a | b can be written as a |= b

10. Bitwise XOR and Assignment (^=): This augmented assignment operator combines the functionality of the bitwise XOR operator and assignment operator. 

a = a ^ b can be written as a ^= b

11. Bitwise Left Shift and Assignment (<<=): It puts together the functioning of the bitwise left shift operator and assignment operator.  

a = a << b can be written as a <<= b

12. Bitwise Right Shift and Assignment (>>=): It puts together the functioning of the bitwise right shift operator and assignment operator.  

a = a >> b can be written as a >>= b

Please Login to comment...

Similar reads.

  • School Learning
  • School Programming
  • 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?

IMAGES

  1. Python Tutorials: Assignment Operators In python

    arithmetic assignment operator in python

  2. Arithmetic Assignment Operator in Python || Basics of Python

    arithmetic assignment operator in python

  3. Python

    arithmetic assignment operator in python

  4. Python Arithmetic Operators and Priority Tutorial

    arithmetic assignment operator in python

  5. Python Operators (Arithmetic, Logical, Relational, Assignment & Bitwise)

    arithmetic assignment operator in python

  6. Arithmetic Operators in Python

    arithmetic assignment operator in python

VIDEO

  1. Assignment Operator

  2. Arithmetic operator using python#shortsvideo #arithmetic operators #python #datascience

  3. Become a Python Expert: Secrets and Guide of Assignment Operator

  4. Vid 5- Operators in Python(Arithmetic, Relational, Assignment & Logical operators)

  5. Assignment & Relational Operator

  6. "Mastering Assignment Operators in Python: A Comprehensive Guide"

COMMENTS

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

  2. Python Operators: Arithmetic, Assignment, Comparison, Logical, Identity

    Python Operators: Arithmetic, Assignment, Comparison, Logical, Identity, Membership, Bitwise. Operators are special symbols that perform some operation on operands and returns the result. For example, 5 + 6 is an expression where + is an operator that performs arithmetic add operation on numeric left operand 5 and the right side operand 6 and ...

  3. Assignment Operators in Python

    Assignment Operator. Assignment Operators are used to assign values to variables. This operator is used to assign the value of the right side of the expression to the left side operand. Python. # Assigning values using # Assignment Operator a = 3 b = 5 c = a + b # Output print(c) Output. 8.

  4. Python Assignment Operators

    Python Assignment Operators. Assignment operators are used to assign values to variables: Operator Example Same As Try it = x = 5: ... Python Operators Tutorial Operators Arithmetic Operators Comparison Operators Logical Operators Identity Operators Membership Operators Bitwise Operators

  5. Python Operators Cheat Sheet

    Here is the complete list of arithmetic operators in Python: Operator. Description. Example. Result + Addition. 2 + 3. 5-Subtraction. 5 - 2. 3 * Multiplication. 4 * 6. 24 / Division. 11 / 4. 2.75 // ... Python Assignment Operators. Assignment operators are used to assign values to variables. They can also perform arithmetic operations in ...

  6. Python Arithmetic Operators

    The Python Operators are used to perform operations on values and variables. These are the special symbols that carry out arithmetic, logical, and bitwise computations. The value the operator operates on is known as the Operand. Here, we will cover Different Assignment operators in Python. Operators Sign Description SyntaxAssignment Operator = Assi

  7. 7. Basic Python Operators: Arithmetic, Comparison, and Assignment

    Diving into Python, one of the most popular programming languages today, it's crucial to grasp the basics. Operators in Python are the building blocks for performing calculations, making decisions, and storing values. I'll walk you through the essentials of arithmetic, comparison, and assignment operators, which are foundational for anyone looking to code in Python.

  8. Python Assignment Operators

    print(num) Run. The above code is useful when we want to update the same number. We can also use two different numbers and use the assignment operators to apply them on two different values. num_one = 6. num_two = 3. print(num_one) num_one += num_two. print(num_one)

  9. Operators and Expressions in Python

    Get to know Python's arithmetic operators and use them to build arithmetic expressions; Explore Python's comparison, Boolean, identity, ... 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 ...

  10. Python Arithmetic Operators: A Complete Guide (50+ Examples)

    Here is the precedence grouping of the arithmetic operators in Python. The upper the operator is on the table, the higher the precedence. Operators Meaning Parentheses ** ... you can combine the addition operator (+) with the assignment operator (=) to form the addition assignment operator (+=). x += y. This is a shorthand for: x = x + y. For ...

  11. Python Operators (With Examples)

    Assignment operators are used to assign values to variables. For example, # assign 5 to x x = 5. Here, = is an assignment operator that assigns 5 to x. Here's a list of different assignment operators available in Python.

  12. Python Assignment Operators

    Multiplication and Assignment Operator. The multiplication and assignment operator multiplies the right-side operand with the left-side operand, and then the result is assigned to the left-hand side operand. Below code is equivalent to: a = a * 2. In [1]: a = 3 a *= 2 print(a) 6.

  13. Arithmetic operators in Python (+, -, *, /, //, %, **)

    Posted: 2023-08-16 | Tags: Python. This article explains the arithmetic operators in Python. For numbers, such as integers (int) and floating point numbers (float), you can perform basic arithmetic operations like addition, subtraction, multiplication, division, and exponentiation. For lists or strings, you can perform operations such as ...

  14. Python Operators

    Python Identity Operators. Identity operators are used to compare the objects, not if they are equal, but if they are actually the same object, with the same memory location: Operator. Description. Example. Try it. is. Returns True if both variables are the same object. x is y.

  15. Operators in Python (arithmetic, comparison, etc.)

    Operators are symbols that perform operations on values in a programming language. In Python, there are several types of operators, including arithmetic, comparison, assignment, logical, and bitwise operators. Understanding these operators and how to use them is a crucial aspect of programming in Python.

  16. PDF Expressions in Python Operators and

    Concatenation and Repetition Augmented Assignment Operators. OperatorDescriptionExample+=Runs an augmented concatenati. operation on the target sequence.Mut. le sequences are updated in place.If the sequence is immutable, then a new sequence is created a. target name.seq_1 += se.

  17. Arithmetic And Assignment Operators In Python

    Assignment operators assign values to variables, they work similar to chalk and blackboard, that is, act as a tool for assignment. For example, a = 10 here, '=' is an assignment operator it gives the variable 'a' which is on the left the value '10' which is on right. Let's look at these operators in detail. This is used to add numbers in a ...

  18. Python

    Python Assignment Operator. The = (equal to) symbol is defined as assignment operator in Python. The value of Python expression on its right is assigned to a single variable on its left. The = symbol as in programming in general (and Python in particular) should not be confused with its usage in Mathematics, where it states that the expressions on the either side of the symbol are equal.

  19. Python Operators

    The Python programming language provides arithmetic operators that perform addition, subtraction, multiplication, and division. It works the same as basic mathematics. ... In Python, Assignment operators are used to assigning value to the variable. Assign operator is denoted by = symbol. For example, ...

  20. Python Assignment Operators

    Operator Multiplication (*=) Operator Division (/=) Operator Modulus (%=) Operator Exponentiation (**=) Operator Floor Division (//=) Conclusion. Python assignment operators are one of the operator types and assign values to variables. We use arithmetic operators here in combination with a variable. Let's take a look at some examples.

  21. 6. Expressions

    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;

  22. Python Operators Explained in Detail with Examples

    Python has seven different types of operators. Arithmetic operators, logic operators, assignment operators, augmented operators, bitwise operators, and two special kinds of operators; membership operator and identity operator. In this tutorial, we learned about each type of these operators by taking different examples.

  23. Augmented Assignment Operators in Python

    The Python Operators are used to perform operations on values and variables. These are the special symbols that carry out arithmetic, logical, and bitwise computations. The value the operator operates on is known as the Operand. Here, we will cover Different Assignment operators in Python. Operators Sign Description SyntaxAssignment Operator = Assi