• Docs »
  • += Addition Assignment
  • Edit on GitHub

+= Addition Assignment ¶

Description ¶.

Adds a value and the variable and assigns the result to that variable.

Return Value ¶

According to coercion rules.

Time Complexity ¶

Equivalent to A = A + B.

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

addition 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

The += Operator In Python – A Complete Guide

FeaImg =Operator

In this lesson, we will look at the += operator in Python and see how it works with several simple examples.

The operator ‘+=’ is a shorthand for the addition assignment operator . It adds two values and assigns the sum to a variable (left operand).

Let’s look at three instances to have a better idea of how this operator works.

1. Adding Two Numeric Values With += Operator

In the code mentioned below, we have initialized a variable X with an initial value of 5 and then add value 15 to it and store the resultant value in the same variable X.

The output of the Code is as follows:

2. Adding Two Strings

In the code mentioned above, we initialized two variables S1 and S2 with initial values as “Welcome to ” and ”AskPython” respectively.

We then add the two strings using the ‘+=’ operator which will concatenate the values of the string.

The output of the code is as follows:

3. Understanding Associativity of “+=” operator in Python

The associativity property of the ‘+=’ operator is from right to left. Let’s look at the example code mentioned below.

We initialized two variables X and Y with initial values as 5 and 10 respectively. In the code, we right shift the value of Y by 1 bit and then add the result to variable X and store the final result to X.

The output comes out to be X = 10 and Y = 10.

Congratulations! You just learned about the ‘+=’ operator in python and also learned about its various implementations.

Liked the tutorial? In any case, I would recommend you to have a look at the tutorials mentioned below:

  • The “in” and “not in” operators in Python
  • Python // operator – Floor Based Division
  • Python Not Equal operator
  • Operator Overloading in Python

Thank you for taking your time out! Hope you learned something new!! 😄

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

Rolex Pearlmaster Replica

A Guide to Python’s += Operator

When writing a program in Python, there's a good chance you will need to add two values and save the resulting value in a variable at some point. 

Doing this is pretty straightforward, even if you don't have much experience programming. But the nice thing is that Python provides an operator to accomplish this quickly.

In this brief tutorial, we'll discuss what this operator is and illustrate how you can use it to add values and assign the result with examples.

A Brief Refresher on Operators

Operators are symbols in Python that represent a pre-defined operation in the language. The first thing that will likely strike you is the plus sign, which represents addition. Of course, there are several operators in Python. 

Let's say you want to keep a running total of a couple of numbers. Here's a simple program you could write:

In the first line, we assigned 10 to the runningTotal variable. 

Then, we added 7.5 to the value in runningTotal and saved this sum in runningTotal.

Finally, we printed the value of runningTotal. 

As you can guess, this program would print 17.5.

Now, let's look at how the += operator can make this program easier to write.

The Python += Operator: Explanation and Examples

The += operator is a pre-defined operator that adds two values and assigns the sum to a variable. For this reason, it's termed the "addition assignment" operator.

The operator is typically used to store sums of numbers in counter variables to keep track of the frequency of repetitions of a specific operation.

Like any other operator, this one also has syntax associated with it. Here's how you'll need to use it so it works correctly:

It's important to note that the variable you set needs to either be a number or a string . The number may be an integer or a floating-point number.

Let's say you initially assign a string value to the variable. Then, the value you write after the equals sign will be appended to the end of the string. 

On the other hand, if a number is initially assigned to a variable, the number after the equals sign will be added to the initially assigned number.

Let's look at an example of both cases:

Numerical Example

Let's rewrite the program we discussed at the beginning of this post. Here's how you would use the addition assignment operator in the program:

Running this code will give you the same result as the program we wrote earlier. 

First, the value 10 will be assigned to runningTotal. The second statement will then add 7.5 to runningTotal.

Finally, the runningTotal value will be printed, and you will see 17.5 appear in the console. 

Using this operator instead of basing the code on the basic logic used in the previous program makes it more "Pythonic." Also, the program is much easier to read and quicker to write. 

String Example

Let's say we define a variable that stores the user's first name. The value of this variable is Chloe. 

Then, we define a second variable to hold the user's surname. The value of this variable is Reid.  

The code would look like this:

We now want to add these names, or rather, append them and store it as one value. We can use the addition operator to do this. 

As you can see, the surname has a space at the beginning. We do this because the addition operator will not add a space to the stored string. 

To merge the two names, we'd use this code:

The code will return the value "Chloe Reid." 

Associativity of the += Operator

Let's use an example to determine the associativity of the addition assignment operator. 

As you can see, variables A and B are assigned values 5 and 10. Then, the value of B is shifted to the right by one bit. The bit-shifted result is then added to A and stored in A.

The final statement prints the A value, showing that it equals 10. So, the associativity property of the addition assignment operator is from left to right.

Other Assignment Operators You Should Know About

Besides the addition assignment operator, Python offers a variety of other assignment operators. Some of the most interesting ones include comparison operators , membership operators, and identity operators.

Assignment operators allow you to perform mathematical functions and assign the results to a variable. Here's a list of what are considered the "main" assignment operators in Python:

+=

Addition

val += 2

val = val + 2

/=

Division

val /= 2

val = val / 2

=

Equals

val = 2

val = 2

*=

Multiplication

val *= 2

val = val * 2

**

Power

val ** 2

val = val ** 2

-=

Subtraction

val -= 2

val = val – 2

With this guide handy, you're prepared to use the addition assignment operator to its full potential. You can also experiment with the other operators mentioned in the table above.

You're now one step closer to mastering Python. You might have a long way to go, but as long as you continue learning, experimenting, and repeating, you will keep making progress and becoming a better programmer.

  • Python Tips and Tricks
  • Python Library Tutorials
  • Python How To's

Related Articles

  • Introduction to Python Classes (Part 2 of 2)
  • Introduction to Python Classes (Part 1 of 2)
  • Fun With Python Function Parameters
  • What is A Tuple in Python
  • Top Python Interview Questions You Should Know the Answer to for a Well-Paying Job

Signup for new content

Thank you for joining our mailing list!

Latest Articles

  • Flask vs. Django: a Comparison of Python Frameworks
  • SaaS development costs overview
  • Proxy Server Creation with Python: A Detailed Guide
  • From Design to Deployment: How Frontend Development Companies Ensure Seamless User Experiences
  • The Benefits of Choosing a Python Software Development Company for Your Next Project
  • Programming language
  • remove python
  • concatenate string
  • Code Editors
  • reset_index()
  • Train Test Split
  • Local Testing Server
  • Python Input
  • priority queue
  • web development
  • uninstall python
  • python string
  • code interface
  • round numbers
  • train_test_split()
  • Flask module
  • Linked List
  • machine learning
  • compare string
  • pandas dataframes
  • arange() method
  • Singly Linked List
  • python scripts
  • learning python
  • python bugs
  • ZipFunction
  • plus equals
  • np.linspace
  • SQLAlchemy advance
  • Data Structure
  • csv in python
  • logging in python
  • Python Counter
  • python subprocess
  • numpy module
  • Python code generators
  • python tutorial
  • csv file python
  • python logging
  • Counter class
  • Python assert
  • numbers_list
  • binary search
  • Insert Node
  • Python tips
  • python dictionary
  • Python's Built-in CSV Library
  • logging APIs
  • Constructing Counters
  • Matplotlib Plotting
  • any() Function
  • linear search
  • Python tools
  • python update
  • logging module
  • Concatenate Data Frames
  • python comments
  • Recursion Limit
  • Data structures
  • installation
  • python function
  • pandas installation
  • Zen of Python
  • concatenation
  • Echo Client
  • NumPy Pad()
  • install python
  • how to install pandas
  • Philosophy of Programming
  • concat() function
  • Socket State
  • Python YAML
  • remove a node
  • function scope
  • Tuple in Python
  • pandas groupby
  • socket programming
  • Python Modulo
  • Dictionary Update()
  • datastructure
  • bubble sort
  • find a node
  • calling function
  • GroupBy method
  • Np.Arange()
  • Modulo Operator
  • Python Or Operator
  • Python salaries
  • pyenv global
  • NumPy arrays
  • insertion sort
  • in place reversal
  • learn python
  • python packages
  • zeros() function
  • Scikit Learn
  • HTML Parser
  • circular queue
  • effiiciency
  • python maps
  • Num Py Zeros
  • Python Lists
  • HTML Extraction
  • selection sort
  • Programming
  • install python on windows
  • reverse string
  • python Code Editors
  • pandas.reset_index
  • Infinite Numbers in Python
  • Python Readlines()

addition assignment operator in python

😶 Operators

Python operators are the symbols that allow us to perform different types of operations on variables and values. They are the building blocks of any programming language, and Python is no exception. Python provides a wide range of operators that can be used to perform arithmetic, logical, comparison, assignment, and bitwise operations.

Understanding the different types of operators is crucial to writing efficient and error-free code in Python. In this section, we will explore the different types of operators available in Python and learn how to use them effectively in our programs. So buckle up and get ready to dive into the world of Python operators!

I. Arithmetic Operators

Arithmetic operators are used in Python to perform basic arithmetic operations such as addition, subtraction, multiplication, division, and more. These operators are used on numeric data types such as integers, floats, and complex numbers.

Python provides the following arithmetic operators:

OperatorNameExampleResult

The floor division (//) operator returns the largest integer that is less than or equal to the division result.

a. Addition

Addition is one of the most basic arithmetic operations in Python. It is denoted by the + symbol and is used to add two numbers or concatenate two strings. For example, if we want to add two numbers x and y together, we can use the + operator like this:

Similarly, if we want to concatenate two strings a and b , we can use the + operator like this:

In both cases, the + operator performs the desired operation and returns a new value that we can assign to a variable or use directly.

b. Subtraction

The subtraction operator (-) is used to subtract one value from another. It takes two operands and returns the difference between them. For example, 5 - 3 will return 2, and 10.5 - 3.2 will return 7.3.

In Python, the subtraction operator can also be used with variables. For example:

Note that the subtraction operator can also be used with negative numbers. For example, 5 - (-3) will return 8.

c. Multiplication

Multiplication is a mathematical operation that is represented by the symbol * in Python. It is used to find the product of two or more values. Here's an example:

In the above example, we have two variables a and b with values 10 and 5 respectively. We multiply these two variables using the * operator and store the result in the variable c . Finally, we print the value of c which is 50 (the product of a and b ).

d. Division

In Python, the / operator is used for division. It returns the quotient (result of division) in the form of a float, even if both the operands are integers. If you want to get the quotient as an integer, you can use the // operator, which performs floor division.

Here's an example:

In the example above, we divide a by b using both the / and // operators. The result of the floating point division is stored in c , which is a float, while the result of the integer division is stored in d , which is an integer.

Modulus operator returns the remainder of the division operation between two operands. It is represented by the percentage sign % .

For example, the expression 9 % 4 returns 1 because when 9 is divided by 4, the remainder is 1.

Here is an example code snippet:

e. Exponentiation

Exponentiation is another arithmetic operator in Python represented by the double asterisk symbol (**). It raises the first operand to the power of the second operand.

Here, the base is the first operand, and the exponent is the second operand.

In the above example, 2 is raised to the power of 3, which results in 8.

f. Floor Division

Floor Division operator in Python is represented by two forward slashes // and it returns the quotient of the division operation rounding down to the nearest integer. For example, the floor division of 7 // 3 would be 2 since 3 goes into 7 two whole times with 1 left over.

Here's an example of using floor division operator:

In the above example, we have defined two variables a and b , and then used floor division operator // to divide a by b . Since a is 10 and b is 3 , the result of a // b is 3 .

II. Comparison Operators

Comparison operators, also known as relational operators, are used to compare two values or operands. In Python, comparison operators always return a boolean value - either True or False.

There are six comparison operators in Python:

Equal to (==)

Not equal to (!=)

Greater than (>)

Less than (<)

Greater than or equal to (>=)

Less than or equal to (<=)

These operators are used in conditional statements and loops to test whether a certain condition is true or false.

a. Equal to (==)

The equal to operator ( == ) is a comparison operator used to compare the equality of two operands. It returns True if the values of the two operands are equal, otherwise, it returns False .

In this example, the first comparison returns False because x is not equal to y . The second comparison returns True because x is equal to z .

b. Not equal to (!=)

In Python, the "not equal to" operator is represented by the exclamation mark followed by an equal sign (!=). It is a binary operator and is used to compare two values. The operator returns True if the values are not equal and False if they are equal.

Here's an example of using the "not equal to" operator in Python:

c. Greater than (>)

The greater than operator ( > ) is used to check if the left operand is greater than the right operand. It returns True if the left operand is greater than the right operand, otherwise, it returns False . Here is an example:

In the example above, x is greater than y , so the expression x > y returns True .

d. Less than (<)

In Python, the less than operator < is used to compare two operands. It returns True if the left operand is less than the right operand, and False otherwise.

In this example, x is less than y , so the if statement evaluates to True , and the first print statement is executed.

e. Greater than or equal to (>=)

The greater than or equal to operator (>=) is used to compare two values. It returns True if the left operand is greater than or equal to the right operand, and False otherwise.

For example:

In this example, the first print statement returns True because x (which is 5) is greater than or equal to y (which is 3). The second print statement returns False because y is less than x .

f. Less than or equal to (<=)

The "Less than or equal to" operator is represented by the symbol "<=". It is used to check if one value is less than or equal to another value.

For example, in the expression "5 <= 10", the operator "<=" checks if 5 is less than or equal to 10. Since this is true, the expression evaluates to True. However, in the expression "10 <= 5", the operator "<=" checks if 10 is less than or equal to 5. Since this is false, the expression evaluates to False.

Here's an example code snippet demonstrating the use of the "<=" operator:

This code will output "x is less than or equal to y", since 5 is indeed less than or equal to 10.

III. Logical Operators

Python Logical Operators are used to combine two or more conditions and perform logical operations on them. The following are the three logical operators in Python:

These operators are used to perform logical operations on the operands and return a Boolean value.

The 'and' operator returns True if both operands are True, otherwise, it returns False.

The 'or' operator returns True if either of the operands is True, otherwise, it returns False.

The 'not' operator returns the opposite of the operand.

Let's look at depth with some examples to understand how these operators work.

The and operator returns True if both operands are true and returns False if either one of the operands is false.

Here's the truth table for the and operator:

Operand 1Operand 2Result

Here's an example code snippet:

In this example, the and operator is used to check if x is smaller than both y and z . If this condition is true, then the statement "x is the smallest number" is printed.

The OR operator in Python is represented by or . It is a logical operator that returns True if at least one of the operands is True , and False otherwise. Here are the possible truth tables for the OR operator:

Operand 1Operand 2Result

Here's an example of using the OR operator in Python:

In this example, x is not greater than y or z , so the output will be x is not greater than y or z .

The NOT operator is a unary operator that negates the value of its operand. In Python, the NOT operator is represented by the keyword "not".

The NOT operator returns True if its operand is False, and vice versa. Here's an example:

In this example, the value of x is True. However, the NOT operator negates the value of x and returns False.

IV. Assignment Operators

Have you ever wanted to quickly assign or modify a value in Python without writing a lot of code? That's where assignment operators come in handy! They allow you to perform an operation on a variable and assign the result back to the same variable in a single step. In this section, we will explore the different types of assignment operators in Python.

a. Simple Assignment Operator

The simple assignment operator in Python is denoted by the equal sign "=" and is used to assign a value to a variable. The syntax for simple assignment is:

where variable is the name of the variable and value is the value to be assigned to the variable.

For example, the following code assigns the value 10 to the variable x :

After executing this code, the variable x will have the value 10 .

b. Arithmetic Assignment Operators

Arithmetic assignment operators are a shorthand way of performing arithmetic operations and assignment at the same time. These operators include:

+= : adds the value of the right operand to the value of the left operand and assigns the result to the left operand.

-= : subtracts the value of the right operand from the value of the left operand and assigns the result to the left operand.

*= : multiplies the value of the left operand by the value of the right operand and assigns the result to the left operand.

/= : divides the value of the left operand by the value of the right operand and assigns the result to the left operand.

%= : computes the modulus of the value of the left operand and the value of the right operand, and assigns the result to the left operand.

//= : performs floor division on the value of the left operand and the value of the right operand, and assigns the result to the left operand.

**= : raises the value of the left operand to the power of the value of the right operand, and assigns the result to the left operand.

These operators can be used with numeric values and variables of numeric types, such as integers and floating-point numbers.

In each of the above examples, the arithmetic operation and the assignment operation are performed at the same time using the shorthand arithmetic assignment operator.

c. Bitwise Assignment Operators

Bitwise assignment operators are used to perform a bitwise operation on a variable and then assign the result to the same variable. The bitwise assignment operators include:

&= : Performs a bitwise AND operation on the variable and the value on the right, then assigns the result to the variable.

|= : Performs a bitwise OR operation on the variable and the value on the right, then assigns the result to the variable.

^= : Performs a bitwise XOR operation on the variable and the value on the right, then assigns the result to the variable.

<<= : Performs a left shift operation on the variable by the number of bits specified on the right, then assigns the result to the variable.

>>= : Performs a right shift operation on the variable by the number of bits specified on the right, then assigns the result to the variable.

d. Logical Assignment Operators

There are no specific "Logical Assignment Operators" in Python, as the logical operators and , or , and not are already used for combining and negating boolean expressions. However, it is possible to use logical operators in combination with assignment operators to create compound expressions, such as x += y or z , which assigns the value of y to x if y is truthy, or the value of z otherwise.

e. Comparison Assignment Operators

There is no such thing as "Comparison Assignment Operators". The term "comparison operator" refers to operators that compare two values and return a boolean value (True or False), while "assignment operator" refers to operators that assign a value to a variable.

However, there are shorthand ways to perform a comparison and assign the result to a variable in a single line of code. For example:

x = 10 if a > b else 20 : This assigns the value 10 to x if a > b is True, otherwise it assigns the value 20.

x += 1 if a == b else 2 : This adds 1 to x if a == b is True, otherwise it adds 2.

x *= 2 if a < b else 3 : This multiplies x by 2 if a < b is True, otherwise it multiplies it by 3.

V. Bitwise Operators

Bitwise operators are used to manipulate the individual bits of binary numbers. In Python, bitwise operators can be applied to integers. The bitwise operators take two operands and operate on them bit by bit to produce a result. There are six bitwise operators in Python: AND, OR, XOR, NOT, left shift, and right shift. These operators are commonly used in low-level programming, such as device driver development and network packet processing.

a. Bitwise AND

The bitwise AND operator is represented by the & symbol in Python. It performs a logical AND operation on each corresponding bit of its operands. If both bits are 1, the resulting bit is 1. Otherwise, the resulting bit is 0.

In this example, a and b are two integers represented in binary. The & operator is used to perform a bitwise AND operation on the two numbers, resulting in the binary number 0010 , which is equivalent to the decimal number 2. The resulting value is assigned to the variable c .

b. Bitwise OR

Bitwise OR is another binary operator that operates on two integers and performs a bitwise OR operation on their binary representations. The resulting binary representation is converted back to an integer.

The syntax for the bitwise OR operator is the pipe symbol | . For example, a | b performs a bitwise OR operation on a and b .

In the above example, the binary OR operation on a and b results in 0011 1101 , which is equal to 61 in decimal representation.

c. Bitwise XOR

Bitwise XOR (exclusive OR) operator is represented by the symbol ^ in Python. The operator returns a binary number that has a 1 in each bit position where the corresponding bits of either but not both operands are 1.

For example, let's say we have two variables a = 13 and b = 17 . The binary representation of 13 is 1101 and the binary representation of 17 is 10001 . Now, let's perform the bitwise XOR operation on these two variables:

In the above example, the resulting binary number is 11000 , which is equivalent to the decimal number 24 . Therefore, the value of the variable c will be 24 .

Here is another example that demonstrates the use of bitwise XOR:

In this example, we first define a and b as binary numbers using the 0b prefix. We then perform the bitwise XOR operation on these two numbers and store the result in c . The resulting binary number is 0b110 , which is equivalent to the decimal number 6 . Therefore, the value of the variable c will be 6 .

d. Bitwise NOT

Bitwise NOT is a unary operator in Python that flips the bits of a number. It is represented by the tilde (~) symbol. When applied to a binary number, the Bitwise NOT operator returns the complement of the number.

In the above code, the value of x is 7, which is represented in binary as 0000 0111. When we apply the Bitwise NOT operator (~) to x , it flips all the bits of the number, resulting in 1111 1000. The output is in two's complement form, which is the way negative numbers are represented in binary.

VI. Membership Operators

Membership operators are used to test if a sequence is present in an object. In Python, we have two membership operators:

in : Evaluates to True if the sequence is present in the object.

not in : Evaluates to True if the sequence is not present in the object.

These operators are typically used with strings, lists, tuples, and sets to check if a certain element or a sequence of elements is present in them.

VII. Identity Operators

Identity Operators are used to compare the memory locations of two objects. There are two identity operators in Python:

is - Returns True if both variables are the same object.

is not - Returns True if both variables are not the same object.

In this example, x and y have the same values, but they are not the same object. z is assigned the same memory location as x , so x and z are the same object. The is operator returns True when comparing x and z , but False when comparing x and y . The is not operator returns False when comparing x and z , but True when comparing x and y .

Last updated 1 year ago

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

Collectives™ on Stack Overflow

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

Q&A for work

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

Get early access and see previews of new features.

What exactly does += do?

I need to know what += does in Python. It's that simple. I also would appreciate links to definitions of other shorthand tools in Python.

  • compound-assignment

martineau's user avatar

  • 11 object.__iadd__ –  ephemient Commented Jan 30, 2011 at 6:06
  • 1 possible duplicate of What does plus equals (+=) do in Python? –  AndiDog Commented Jan 30, 2011 at 8:22
  • 3 @AndiDog While it's true both questions are about the (+=) operator, the one you linked is about a sophisticated usage and subtle problem, and the OP here is probably not able to follow the reasoning there (yet). –  Dr. belisarius Commented Jan 30, 2011 at 9:42
  • 3 @AndiDog Perhaps you were right at that time, but looking at the (almost) accepted solutions here, is clear that this question is about a basic understanding of the operator :D –  Dr. belisarius Commented Jan 30, 2011 at 9:48
  • 2 Most sumbol uses are now indexed in the Symbols page docs.python.org/3/genindex-Symbols.html . –  Terry Jan Reedy Commented Oct 31, 2014 at 22:04

17 Answers 17

In Python, += is sugar coating for the __iadd__ special method, or __add__ or __radd__ if __iadd__ isn't present. The __iadd__ method of a class can do anything it wants. The list object implements it and uses it to iterate over an iterable object appending each element to itself in the same way that the list's extend method does.

Here's a simple custom class that implements the __iadd__ special method. You initialize the object with an int, then can use the += operator to add a number. I've added a print statement in __iadd__ to show that it gets called. Also, __iadd__ is expected to return an object, so I returned the addition of itself plus the other number which makes sense in this case.

starball's user avatar

  • 35 While this is not what the Asker was looking for, +1 for the real answer. =) –  Michael come lately Commented Feb 18, 2014 at 19:35
  • @Michael, that's where humor adds to the fact... :-D –  Aaron John Sabu Commented Dec 3, 2017 at 10:21
  • 4 +1 for answering the question, but -1 for an __iadd__ that returns a different type (which itself is addable) –  Caleth Commented Jun 1, 2018 at 16:07
  • 5 This answer is too complex for the type of person who would need to ask what += means (i.e., a beginner). Your answer is not a beginner answer, not just because beginners usually don't start learning Python in an object-oriented way, but also because there are much simpler answers (like @Imran's below). Just my two cents, even though I appreciate this answer. –  q-compute Commented Sep 10, 2019 at 15:18
  • 2 @q-compute On the contrary, I think the only legitimate reason to look to StackOverflow for information about what += does in Python would be because you've been tripped up by some of its arcane vagaries and complexities. –  Marcel Besixdouze Commented Apr 13, 2021 at 17:17

+= adds another value with the variable's value and assigns the new value to the variable.

-= , *= , /= does similar for subtraction, multiplication and division.

Imran's user avatar

  • Note that, as the currently most upvoted answer details, x += y is not the same thing as x = x + y , especially if x is a list. See this for an example. (Or this .) –  Pro Q Commented Mar 19 at 7:55

x += 5 is not exactly the same as saying x = x + 5 in Python.

See for reference: Why does += behave unexpectedly on lists?

wjandrea's user avatar

  • it is the same, though, except for the weird case x += 7,8,9 –  Ufos Commented Oct 30, 2019 at 10:44
  • Also, one of the linked threads provides a good discussion on where exactly it differs. stackoverflow.com/questions/6951792/… –  Ufos Commented Oct 30, 2019 at 11:23

+= adds a number to a variable, changing the variable itself in the process (whereas + would not). Similar to this, there are the following that also modifies the variable:

  • -= , subtracts a value from variable, setting the variable to the result
  • *= , multiplies the variable and a value, making the outcome the variable
  • /= , divides the variable by the value, making the outcome the variable
  • %= , performs modulus on the variable, with the variable then being set to the result of it

There may be others. I am not a Python programmer.

Ryan Bigg's user avatar

  • 2 For numbers, this answer is correct. (See Bryan's answer for special behavior.) There are indeed several others, including bitwise operators ( &= , >>= , etc.) and additional math operators ( **= , etc.). –  Michael come lately Commented Dec 21, 2017 at 16:12

It is not mere a syntactic sugar. Try this:

The += operator invokes the __iadd__() list method, while + one invokes the __add__() one. They do different things with lists.

MarianD's user avatar

  • I was so confused about this! Thanks for your code and explanation. It looks like += only works safely for numbers. Am I right? –  user3512680 Commented Feb 18, 2021 at 16:50

It adds the right operand to the left. x += 2 means x = x + 2

It can also add elements to a list -- see this SO thread .

Community's user avatar

Notionally a += b "adds" b to a storing the result in a. This simplistic description would describe the += operator in many languages.

However the simplistic description raises a couple of questions.

  • What exactly do we mean by "adding"?
  • What exactly do we mean by "storing the result in a"? python variables don't store values directly they store references to objects.

In python the answers to both of these questions depend on the data type of a.

So what exactly does "adding" mean?

  • For numbers it means numeric addition.
  • For lists, tuples, strings etc it means concatenation.

Note that for lists += is more flexible than +, the + operator on a list requires another list, but the += operator will accept any iterable.

So what does "storing the value in a" mean?

If the object is mutable then it is encouraged (but not required) to perform the modification in-place. So a points to the same object it did before but that object now has different content.

If the object is immutable then it obviously can't perform the modification in-place. Some mutable objects may also not have an implementation of an in-place "add" operation . In this case the variable "a" will be updated to point to a new object containing the result of an addition operation.

Technically this is implemented by looking for __IADD__ first, if that is not implemented then __ADD__ is tried and finally __RADD__ .

Care is required when using += in python on variables where we are not certain of the exact type and in particular where we are not certain if the type is mutable or not. For example consider the following code.

When we invoke dostuff with a tuple then the tuple is copied as part of the += operation and so b is unaffected. However when we invoke it with a list the list is modified in place, so both a and b are affected.

In python 3, similar behaviour is observed with the "bytes" and "bytearray" types.

Finally note that reassignment happens even if the object is not replaced. This doesn't matter much if the left hand side is simply a variable but it can cause confusing behaviour when you have an immutable collection referring to mutable collections for example:

In this case [5] will successfully be added to the list referred to by a[0] but then afterwards an exception will be raised when the code tries and fails to reassign a[0].

plugwash's user avatar

Note x += y is not the same as x = x + y in some situations where an additional operator is included because of the operator precedence combined with the fact that the right hand side is always evaluated first, e.g.

Note the first case expand to:

You are more likely to encounter this in the 'real world' with other operators, e.g.

x *= 2 + 1 == x = x * (2 + 1) != x = x * 2 + 1

Chris_Rands's user avatar

The short answer is += can be translated as "add whatever is to the right of the += to the variable on the left of the +=".

Ex. If you have a = 10 then a += 5 would be: a = a + 5

So, "a" now equal to 15.

Roman Skydan's user avatar

  • 1 What does this answer contribute that hasn't already been discussed? It's a duplicate Answer... –  user1531971 Commented Jan 15, 2019 at 16:54
  • jdv, just trying to help. I'm a new contributor, so sorry if you think my answer was a duplicate. –  user10917993 Commented Jan 17, 2019 at 20:48
  • It's clear that it is a duplicate if you look at most of the other answers. It's fine to contribute, but you should strive for contributing something new (e.g., like the add vs iadd answer) or you want to take a stab at a clearer solution. But, as far as I can tell, the top-voted answers are about as clear as you can get for a basic answer. –  user1531971 Commented Jan 17, 2019 at 20:54

According to the documentation

x += y is equivalent to x = operator.iadd(x, y) . Another way to put it is to say that z = operator.iadd(x, y) is equivalent to the compound statement z = x; z += y .

So x += 3 is the same as x = x + 3 .

will output 5.

Notice that there are also

Tiago Peres's user avatar

+= is just a shortcut for writing

So instead you would write

Both ways are correct but example two helps you write a little less code

Nicolas Gervais's user avatar

  • 2 The behaviour is the same on numbers but it's not the same in general. –  plugwash Commented May 10, 2018 at 20:29

Let's look at the byte code that CPython generates for x += y and x = x = y . (Yes, this is implementation-depenent, but it gives you an idea of the language-defined semantics being implemented.)

The only difference between the two is the bytecode used for the operator: INPLACE_ADD for += , and BINARY_ADD for + .

BINARY_ADD is implemented using x.__add__ (or y.__radd__ if necessary), so x = x + y is roughly the same as x = x.__add__(y) . Both __add__ and __radd__ typically return new instances, without modifying either argument.

INPLACE_ADD is implemented using x.__iadd__ . If that does not exist, then x.__add__ is used in its place. x.__iadd__ typically returns x , so that the resulting STORE_NAME does not change the referent of x , though that object may have been mutated. (Indeed, the purpose of INPLACE_ADD is to provide a way to mutate an object rather than always create a new object.)

For example, int.__iadd__ is not defined, so x += 7 when x is an int is the same as x = x.__add__(y) , setting x to a new instance of int .

On the other hand, list.__iadd__ is defined, so x += [7] when x is a list is the same as x = x.__iadd__([9]) . list.__iadd__ effectively calls extend to add the elements of its argument to the end of x . It's not really possible to tell by looking at the value of x before and after the augmented assignment that x was reassigned, because the same object was assigned to the name.

chepner's user avatar

As others also said, the += operator is a shortcut. An example:

It could also be written like so:

So instead of writing the first example, you can just write the second one, which would work just fine.

notTypecast's user avatar

Remember when you used to sum, for example 2 & 3, in your old calculator and every time you hit the = you see 3 added to the total, the += does similar job. Example:

salhin's user avatar

I'm seeing a lot of answers that don't bring up using += with multiple integers.

One example:

This would be similar to:

Javier Perez's user avatar

It’s basically a simplification of saying (variable) = (variable) + x For example:

Is the same as:

BenDeagle's user avatar

The += cuts down on the redundancy in adding two objects with a given variable:

Long Version:

Short Version:

Antoine's user avatar

Your Answer

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

Sign up or log in

Post as a guest.

Required, but never shown

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

Not the answer you're looking for? Browse other questions tagged python operators compound-assignment or ask your own question .

  • The Overflow Blog
  • Where does Postgres fit in a world of GenAI and vector databases?
  • Featured on Meta
  • We've made changes to our Terms of Service & Privacy Policy - July 2024
  • Bringing clarity to status tag usage on meta sites
  • What does a new user need in a homepage experience on Stack Overflow?
  • Feedback requested: How do you use tag hover descriptions for curating and do...
  • Staging Ground Reviewer Motivation

Hot Network Questions

  • Fill a grid with numbers so that each row/column calculation yields the same number
  • My Hydraulic brakes are seizing up and I have tried everything. Help
  • Is Intuitionism Indispensable in Mathematics?
  • What would be non-slang equivalent of "copium"?
  • Story where character has "boomerdisc"
  • Simple casino game
  • Are quantum states like the W, Bell, GHZ, and Dicke state actually used in quantum computing research?
  • Is every recursively axiomatizable and consistent theory interpretable in the true arithmetic (TA)?
  • Does Vexing Bauble counter taxed 0 mana spells?
  • A View over java.lang.String - improved take II
  • Why doesn't the world fill with time travelers?
  • How long does it take to achieve buoyancy in a body of water?
  • Passport Carry in Taiwan
  • How can these humans cross the ocean(s) at the first possible chance?
  • The size of elementary particles
  • Why did General Leslie Groves evade Robert Oppenheimer's question here?
  • about flag changes in 16-bit calculations on the MC6800
  • Reusing own code at work without losing licence
  • Using "no" at the end of a statement instead of "isn't it"?
  • Trying to find an old book (fantasy or scifi?) in which the protagonist and their romantic partner live in opposite directions in time
  • "TSA regulations state that travellers are allowed one personal item and one carry on"?
  • Is there a phrase for someone who's really bad at cooking?
  • Exact time point of assignment
  • What to do when 2 light switches are too far apart for the light switch cover plate?

addition assignment operator in python

Arithmetic Operators

Subtraction, multiplication, floor division.

and are added together

is subtracted from

and are multiplied together

divided by ; the result is always a float

divided by ; the result is dependent on the values passed

is raised to the power of

is divided by

For demonstration purposes, let’s take two numbers: num_one , which will be made equal to 6, and num_two , which will be made equal to 3. Applying the operations above would give the following results:

Adding 6 and 3 would result in 9.

Expression: 6 + 3  

Subtracting 3 from 6 would result in 3.

Expression: 6 - 3  

Multiplying 6 and 3 would result in 18.

Expression: 6 * 3  

Dividing 6 by 3 using the / operator would result in 2.0 (always a float).

Expression: 6 / 3

Dividing 6 by 3 using the // operator would result in 2 (since 6 and 3 are integers).

Expression: 6 // 3  

6 to the power of 3 would result in 216.

Expression: 6 ** 3

6 divided by 3 would result in a remainder of 0.

Expression: 6 % 3

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

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

addition 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

01 Career Opportunities

02 beginner, 03 intermediate, 04 training programs, assignment operators in python, what is an assignment operator in python.

.

Types of Assignment Operators in Python

1. simple python assignment operator (=), example of simple python assignment operator, 2. augmented assignment operators in python, 1. augmented arithmetic assignment operators in python.

+=Addition Assignment Operator
-=Subtraction Assignment Operator
*=Multiplication Assignment Operator
/=Division Assignment Operator
%=Modulus Assignment Operator
//=Floor Division Assignment Operator
**=Exponentiation Assignment Operator

2. Augmented Bitwise Assignment Operators in Python

&=Bitwise AND Assignment Operator
|=Bitwise OR Assignment Operator
^=Bitwise XOR Assignment Operator
>>=Bitwise Right Shift Assignment Operator
<<=Bitwise Left Shift Assignment Operator

Augmented Arithmetic Assignment Operators in Python

1. augmented addition operator (+=), example of augmented addition operator in python, 2. augmented subtraction operator (-=), example of augmented subtraction operator in python, 3. augmented multiplication operator (*=), example of augmented multiplication operator in python, 4. augmented division operator (/=), example of augmented division operator in python, 5. augmented modulus operator (%=), example of augmented modulus operator in python, 6. augmented floor division operator (//=), example of augmented floor division operator in python, 7. augmented exponent operator (**=), example of augmented exponent operator in python, augmented bitwise assignment operators in python, 1. augmented bitwise and (&=), example of augmented bitwise and operator in python, 2. augmented bitwise or (|=), example of augmented bitwise or operator in python, 3. augmented bitwise xor (^=), example of augmented bitwise xor operator in python, 4. augmented bitwise right shift (>>=), example of augmented bitwise right shift operator in python, 5. augmented bitwise left shift (<<=), example of augmented bitwise left shift operator in python, walrus operator in python, syntax of an assignment expression, example of walrus operator in python.

Live Classes Schedule

Filling Fast
Filling Fast
Filling Fast
Filling Fast
Filling Fast
Filling Fast
Filling Fast
Filling Fast
Filling Fast
Filling Fast

About Author

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

PrepBytes Blog

ONE-STOP RESOURCE FOR EVERYTHING RELATED TO CODING

Sign in to your account

Forgot your password?

Login via OTP

We will send you an one time password on your mobile number

An OTP has been sent to your mobile number please verify it below

Register with PrepBytes

Assignment operator in python.

' src=

Last Updated on June 8, 2023 by Prepbytes

addition assignment operator in python

To fully comprehend the assignment operators in Python, it is important to have a basic understanding of what operators are. Operators are utilized to carry out a variety of operations, including mathematical, bitwise, and logical operations, among others, by connecting operands. Operands are the values that are acted upon by operators. In Python, the assignment operator is used to assign a value to a variable. The assignment operator is represented by the equals sign (=), and it is the most commonly used operator in Python. In this article, we will explore the assignment operator in Python, how it works, and its different types.

What is an Assignment Operator in Python?

The assignment operator in Python is used to assign a value to a variable. The assignment operator is represented by the equals sign (=), and it is used to assign a value to a variable. When an assignment operator is used, the value on the right-hand side is assigned to the variable on the left-hand side. This is a fundamental operation in programming, as it allows developers to store data in variables that can be used throughout their code.

For example, consider the following line of code:

Explanation: In this case, the value 10 is assigned to the variable a using the assignment operator. The variable a now holds the value 10, and this value can be used in other parts of the code. This simple example illustrates the basic usage and importance of assignment operators in Python programming.

Types of Assignment Operator in Python

There are several types of assignment operator in Python that are used to perform different operations. Let’s explore each type of assignment operator in Python in detail with the help of some code examples.

1. Simple Assignment Operator (=)

The simple assignment operator is the most commonly used operator in Python. It is used to assign a value to a variable. The syntax for the simple assignment operator is:

Here, the value on the right-hand side of the equals sign is assigned to the variable on the left-hand side. For example

Explanation: In this case, the value 25 is assigned to the variable a using the simple assignment operator. The variable a now holds the value 25.

2. Addition Assignment Operator (+=)

The addition assignment operator is used to add a value to a variable and store the result in the same variable. The syntax for the addition assignment operator is:

Here, the value on the right-hand side is added to the variable on the left-hand side, and the result is stored back in the variable on the left-hand side. For example

Explanation: In this case, the value of a is incremented by 5 using the addition assignment operator. The result, 15, is then printed to the console.

3. Subtraction Assignment Operator (-=)

The subtraction assignment operator is used to subtract a value from a variable and store the result in the same variable. The syntax for the subtraction assignment operator is

Here, the value on the right-hand side is subtracted from the variable on the left-hand side, and the result is stored back in the variable on the left-hand side. For example

Explanation: In this case, the value of a is decremented by 5 using the subtraction assignment operator. The result, 5, is then printed to the console.

4. Multiplication Assignment Operator (*=)

The multiplication assignment operator is used to multiply a variable by a value and store the result in the same variable. The syntax for the multiplication assignment operator is:

Here, the value on the right-hand side is multiplied by the variable on the left-hand side, and the result is stored back in the variable on the left-hand side. For example

Explanation: In this case, the value of a is multiplied by 5 using the multiplication assignment operator. The result, 50, is then printed to the console.

5. Division Assignment Operator (/=)

The division assignment operator is used to divide a variable by a value and store the result in the same variable. The syntax for the division assignment operator is:

Here, the variable on the left-hand side is divided by the value on the right-hand side, and the result is stored back in the variable on the left-hand side. For example

Explanation: In this case, the value of a is divided by 5 using the division assignment operator. The result, 2.0, is then printed to the console.

6. Modulus Assignment Operator (%=)

The modulus assignment operator is used to find the remainder of the division of a variable by a value and store the result in the same variable. The syntax for the modulus assignment operator is

Here, the variable on the left-hand side is divided by the value on the right-hand side, and the remainder is stored back in the variable on the left-hand side. For example

Explanation: In this case, the value of a is divided by 3 using the modulus assignment operator. The remainder, 1, is then printed to the console.

7. Floor Division Assignment Operator (//=)

The floor division assignment operator is used to divide a variable by a value and round the result down to the nearest integer, and store the result in the same variable. The syntax for the floor division assignment operator is:

Here, the variable on the left-hand side is divided by the value on the right-hand side, and the result is rounded down to the nearest integer. The rounded result is then stored back in the variable on the left-hand side. For example

Explanation: In this case, the value of a is divided by 3 using the floor division assignment operator. The result, 3, is then printed to the console.

8. Exponentiation Assignment Operator (**=)

The exponentiation assignment operator is used to raise a variable to the power of a value and store the result in the same variable. The syntax for the exponentiation assignment operator is:

Here, the variable on the left-hand side is raised to the power of the value on the right-hand side, and the result is stored back in the variable on the left-hand side. For example

Explanation: In this case, the value of a is raised to the power of 3 using the exponentiation assignment operator. The result, 8, is then printed to the console.

9. Bitwise AND Assignment Operator (&=)

The bitwise AND assignment operator is used to perform a bitwise AND operation on the binary representation of a variable and a value, and store the result in the same variable. The syntax for the bitwise AND assignment operator is:

Here, the variable on the left-hand side is ANDed with the value on the right-hand side using the bitwise AND operator, and the result is stored back in the variable on the left-hand side. For example,

Explanation: In this case, the value of a is ANDed with 3 using the bitwise AND assignment operator. The result, 2, is then printed to the console.

10. Bitwise OR Assignment Operator (|=)

The bitwise OR assignment operator is used to perform a bitwise OR operation on the binary representation of a variable and a value, and store the result in the same variable. The syntax for the bitwise OR assignment operator is:

Here, the variable on the left-hand side is ORed with the value on the right-hand side using the bitwise OR operator, and the result is stored back in the variable on the left-hand side. For example,

Explanation: In this case, the value of a is ORed with 3 using the bitwise OR assignment operator. The result, 7, is then printed to the console.

11. Bitwise XOR Assignment Operator (^=)

The bitwise XOR assignment operator is used to perform a bitwise XOR operation on the binary representation of a variable and a value, and store the result in the same variable. The syntax for the bitwise XOR assignment operator is:

Here, the variable on the left-hand side is XORed with the value on the right-hand side using the bitwise XOR operator, and the result are stored back in the variable on the left-hand side. For example,

Explanation: In this case, the value of a is XORed with 3 using the bitwise XOR assignment operator. The result, 5, is then printed to the console.

12. Bitwise Right Shift Assignment Operator (>>=)

The bitwise right shift assignment operator is used to shift the bits of a variable to the right by a specified number of positions, and store the result in the same variable. The syntax for the bitwise right shift assignment operator is:

Here, the variable on the left-hand side has its bits shifted to the right by the number of positions specified by the value on the right-hand side, and the result is stored back in the variable on the left-hand side. For example,

Explanation: In this case, the value of a is shifted 2 positions to the right using the bitwise right shift assignment operator. The result, 2, is then printed to the console.

13. Bitwise Left Shift Assignment Operator (<<=)

The bitwise left shift assignment operator is used to shift the bits of a variable to the left by a specified number of positions, and store the result in the same variable. The syntax for the bitwise left shift assignment operator is:

Here, the variable on the left-hand side has its bits shifted to the left by the number of positions specified by the value on the right-hand side, and the result is stored back in the variable on the left-hand side. For example,

Conclusion Assignment operator in Python is used to assign values to variables, and it comes in different types. The simple assignment operator (=) assigns a value to a variable. The augmented assignment operators (+=, -=, *=, /=, %=, &=, |=, ^=, >>=, <<=) perform a specified operation and assign the result to the same variable in one step. The modulus assignment operator (%) calculates the remainder of a division operation and assigns the result to the same variable. The bitwise assignment operators (&=, |=, ^=, >>=, <<=) perform bitwise operations and assign the result to the same variable. The bitwise right shift assignment operator (>>=) shifts the bits of a variable to the right by a specified number of positions and stores the result in the same variable. The bitwise left shift assignment operator (<<=) shifts the bits of a variable to the left by a specified number of positions and stores the result in the same variable. These operators are useful in simplifying and shortening code that involves assigning and manipulating values in a single step.

Here are some Frequently Asked Questions on Assignment Operator in Python:

Q1 – Can I use the assignment operator to assign multiple values to multiple variables at once? Ans – Yes, you can use the assignment operator to assign multiple values to multiple variables at once, separated by commas. For example, "x, y, z = 1, 2, 3" would assign the value 1 to x, 2 to y, and 3 to z.

Q2 – Is it possible to chain assignment operators in Python? Ans – Yes, you can chain assignment operators in Python to perform multiple operations in one line of code. For example, "x = y = z = 1" would assign the value 1 to all three variables.

Q3 – How do I perform a conditional assignment in Python? Ans – To perform a conditional assignment in Python, you can use the ternary operator. For example, "x = a (if a > b) else b" would assign the value of a to x if a is greater than b, otherwise it would assign the value of b to x.

Q4 – What happens if I use an undefined variable in an assignment operation in Python? Ans – If you use an undefined variable in an assignment operation in Python, you will get a NameError. Make sure you have defined the variable before trying to assign a value to it.

Q5 – Can I use assignment operators with non-numeric data types in Python? Ans – Yes, you can use assignment operators with non-numeric data types in Python, such as strings or lists. For example, "my_list += [4, 5, 6]" would append the values 4, 5, and 6 to the end of the list named my_list.

Leave a Reply Cancel reply

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

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

  • Linked List
  • Segment Tree
  • Backtracking
  • Dynamic Programming
  • Greedy Algorithm
  • Operating System
  • Company Placement
  • Interview Tips
  • General Interview Questions
  • Data Structure
  • Other Topics
  • Computational Geometry
  • Game Theory

Related Post

Python list functions & python list methods, python interview questions, namespaces and scope in python, what is the difference between append and extend in python, python program to check for the perfect square, python program to find the sum of first n natural numbers.

  • 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

Python Arithmetic Operators

The Python operators are fundamental for performing mathematical calculations in programming languages like Python, Java, C++, and many others. Arithmetic operators are symbols used to perform mathematical operations on numerical values. In most programming languages, arithmetic operators include addition (+), subtraction (-), multiplication (*), division (/), and modulus (%).

Arithmetic Operators in Python

There are 7 arithmetic operators in Python . The lists are given below:


Operator

Description

Syntax

+

Addition: adds two operands

x + y

Subtraction: subtracts two operands

x – y

*

Multiplication: multiplies two operands

x * y

/

Division (float): divides the first operand by the second

x / y

//

Division (floor): divides the first operand by the second

x // y

%

Modulus: returns the remainder when the first operand is divided by the second

x % y

**

Power (Exponent): Returns first raised to power second

x ** y

Precedence of Arithmetic Operators in Python

Let us see the precedence and associativity of Python Arithmetic operators.

Operator

Description

Associativity

Exponentiation Operator

right-to-left

Modulos, Multiplication, Division, and Floor Division

left-to-right

Addition and Subtraction operators

left-to-right

Addition Operator

In Python, + is the addition operator. It is used to add 2 values.

Output: 

Subtraction Operator

In Python, – is the subtraction operator. It is used to subtract the second value from the first value.

Multiplication Operator

Python * operator is the multiplication operator. It is used to find the product of 2 values.

Output : 

Division Operator 

Python // operator is the division operator. It is used to find the quotient when the first operand is divided by the second.

Floor Division Operator

The // in Python is used to conduct the floor division. It is used to find the floor of the quotient when the first operand is divided by the second.

Modulus Operator

The % in Python is the modulus operator. It is used to find the remainder when the first operand is divided by the second. 

Exponentiation Operator

In Python, ** is the exponentiation operator. It is used to raise the first operand to the power of the second. 

Python Arithmetic Operators – FAQs

What are the 7 arithmetic operators in python.

Python has seven basic arithmetic operators used to perform mathematical operations: Addition ( + ) : Adds two numbers. result = 3 + 2 # Output: 5 Subtraction ( - ) : Subtracts one number from another. result = 5 - 2 # Output: 3 Multiplication ( * ) : Multiplies two numbers. result = 3 * 2 # Output: 6 Division ( / ) : Divides one number by another, returning a float. result = 6 / 2 # Output: 3.0 Floor Division ( // ) : Divides one number by another, returning an integer. result = 7 // 2 # Output: 3 Modulus ( % ) : Returns the remainder of a division. result = 7 % 2 # Output: 1 Exponentiation ( ** ) : Raises one number to the power of another. result = 3 ** 2 # Output: 9

What are the 6 relational operators in Python?

Python has six relational operators used to compare values: Equal to ( == ) : Checks if two values are equal. Not equal to ( != ) : Checks if two values are not equal. Greater than ( > ) : Checks if the left value is greater than the right value. Less than ( < ) : Checks if the left value is less than the right value. Greater than or equal to ( >= ) : Checks if the left value is greater than or equal to the right value. Less than or equal to ( <= ) : Checks if the left value is less than or equal to the right value.

What is the rule for arithmetic operators in Python?

Arithmetic operators in Python follow the standard mathematical order of operations, also known as BODMAS/BIDMAS rules: B rackets O rders (exponentiation, ** ) D ivision and M ultiplication ( / , * , // , % ) A ddition and S ubtraction ( + , - ) result = 3 + 2 * 2 ** 2 / 2 - 1 # Output: 6.0 # Explanation: 3 + ((2 * (2 ** 2)) / 2) - 1 # 3 + ((2 * 4) / 2) - 1 # 3 + (8 / 2) - 1 # 3 + 4 - 1 # 7 - 1 # 6.0

What is the === in Python?

Python does not have a === operator. In many other programming languages like JavaScript, === is a strict equality operator that checks both the value and the type. In Python, you use == to check for equality and is to check for identity (if two references point to the same object).

What is the arithmetic operator?

An arithmetic operator is a symbol that performs a mathematical operation on one or more operands. The basic arithmetic operators in Python include addition ( + ), subtraction ( - ), multiplication ( * ), division ( / ), floor division ( // ), modulus ( % ), and exponentiation ( ** ). These operators are used to perform calculations and return a numeric result.

Please Login to comment...

Similar reads.

  • python-basics
  • Python-Operators
  • SUMIF in Google Sheets with formula examples
  • How to Get a Free SSL Certificate
  • Best SSL Certificates Provider in India
  • Elon Musk's xAI releases Grok-2 AI assistant
  • Content Improvement League 2024: From Good To A Great Article

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

Defining a symbolic syntax for referring to assignment targets

FWIW, aside from the potential performance hit, mutating f_locals should work reliably in 3.13+ due to PEP 667 – Consistent views of namespaces | peps.python.org

I actually had thought about that too but the problem was that we can’t use a soft keyword for it since there is no way syntactically to distinguish the soft keyword from a variable name, and if we make it a hard keyword then it would be too much of a breaking change since the keyword would have to be a commonly used English word that likely collides with variable names in existing code base.

But now it occurred to me that we can just make the magic placeholder a dunder so no existing code base should be using it. As for the name itself, I think __target__ would be good:

The code now looks a lot less cryptic/Perlish to me.

Behind the scene though, __target__ would be a hard keyword rather than a variable name. It won’t be looked up in the namespace but is rather expanded at compilation time.

Similarlly, @'' can be made into a new hard keyword such as __target_name__ to look less cryptic.

Yup, same here. I almost wrote my own POV comparing this to walrus, but decided not to half-way through realising that it isn’t going to be of much use given this is currently at contemplative stage.

And it took me a fair bit of time to stop abusing walrus, however I am happy about it having finally learned to use it responsibly.

The notation, I think is decent - visually and semantically. And been wandering what was the reason for @ for mat_mult - never seen @ used anywhere in math before. There was quite a good example for this - matlab . Can’t do exactly the same, but retaining * might have been better, e.g. \* . So that @ could be used for something more appropriate, e.g. this. But given status quo, I don’t think it would fly. So 2 options:

  • Change matrix multiplication operator. Been thinking about how hard of a sell this would be. I know that no-one would want to do it. All the backwards compatibility etc, but has anyone analysed compound cost of a bad decision? And the fact that the earlier the correction is done, the smaller the damage? I am talking in general, not only this specific case. I mean surely if the goal is best possible version of Python, (as opposed to pleasing unsatisfied and reluctant to adapt users), big breaks of backwards compatibility are inevitable…
  • Pick something else for this. One idea would be to go with bash-like argument syntax, but with pythonic slicing:

Or maybe even star, given it being used in expansions:

Could also incorporate string-like formatting:

Alternatively, use * for strings, @ for values (similar to what bash does).

We have space-separated names as arguments in the standard library too, such as collections.namedtuple and enum.Enum :

Using my dunder keyword idea above, it can become:

The matrix multiplication PEP did cover that: PEP 465 – A dedicated infix operator for matrix multiplication | peps.python.org

The __target__ dunder idea is interesting, as it doesn’t provide brevity gains in most cases, but does provide the benefit of avoiding repeated evaluation.

I suspect code that assigns to identifiers would continue to be better off just using the target identifier directly, but attribute access, subscripting, slicing, and tuple assignment could still see some utility.

__target_text__ could replace @'' for both identifier assignment and tuple assignment ( __target_name__ wouldn’t match the latter use case)

I doubt you could reasonably use that form to map function parameters to local variables of the same name, though.

Sounds good indeed. With the name __target_text__ we wouldn’t have to worry about a plural form.

I don’t see why not. We can name the new keyword that forwards local variables to function parameters of the same names, __same__ . The compiler with access to AST can clearly tell which keyword argument a ast.Same node belongs to and produces bytecode that loads the local variable of that name for the argument accordingly:

This is really a completely separate proposal from the assignment target placeholder proposal though, and should be discussed about in a separate thread (perhaps in the PEP-736 thread, in which I have now made a post ).

Yeah the loss of brevity does take away the utility of this idea in cases of a single identifier, particularly as an alternative to PEP-736, where parameter names are always single identifiers.

I agree that we should focus more on its utility for more complex assignment targets.

Going further on the SymPy tangent, I can brainstorm a possible story of how to get that by more straightforward extensions of existing syntax.

The hardest hurdle in this story is the first step. Suppose Python somehow gets dict destructuring assignment:

Sympy then defines a helper whose __getitem__ gives out symbols (if it doesn’t already have it):

By this time PEP 736 has been accepted, and its syntax gets extended to dict destructuring:

(Is that Perlish?) (Is it the direction Python is going?)

People now start writing {Point2D=} = namedtuplemaker('x', 'y') … which isn’t straightforward to read today, but maybe it’s better than with @'' ?

“Whatever, we have to pick something.”

If you’re going to give the target a full identifier, you might as well provide the name rather than hardcoding it

some.nested.attribute as x = x.lower()

This doesn’t require new tokens, and the syntax mimics what we have in the match statement (which tries to overlap assignment syntax). It definitely looks more python than perl (keywords vs symbols)

Same as your proposal, this doesn’t cover argument pushing, but only double evaluation (at this point it isn’t much more than a glorified walrus). This is also missing a syntax to capture the name of the target as a str. I’m not sorry convinced on that but I think you could do (a, b, c) as (_, names) = simpy.symbols(names) .

I’m not super sold into this either, but hopefully putting this idea on the table may help someone find a better proposal

For me a big part of this feature was not needing to assign a name for this specific “some.nested.attribute”, so I’m not really sure I like the as proposal

A benefit can be that if the name persists, it can be used more times in the code that follows the assignment.

Quite like it, one issue though:

While naming tuple thing obstruct such intuitive expansion. However might not be an issue as one can always slice it on the right hand side. However, it does not seem very elegant nevertheless. Maybe something like:

This would be the 2nd method that allows extracting identifier name from identifier. First one being f{a=} . However, it would also be the second one which compulsory does more than that, while simple straight forward way to do this still does not exist, namely something similar to C# nameof , that would do exactly that without needing to evaluate anything. Thinking if I could hack this for it:

Interesting idea, for sure.

What I don’t like about it is that it encourages a coding style that binds multiple different values to the same name. Inevitably, one of those values is going to be badly named.

E.g. you might see

At point (1) , the value of sth.this_must_be_lowercase violates requirements: The value is in fact not guaranteed lowercase.

I would rather it was written such that different values have different names. Like this:

This is a fairly marginal coding style distinction, and not something I would usually make a fuss about. But I do think the latter style is marginally better, and it would be unfortunate to add syntax that encourages the former style.

I am -1 to using @ for any of the purposes outlined here, but +1 to long_name as x = foo(x) being sugar for long_name = foo('long_name') .

It should work the same for dotted names and tuples, i.e. a.b. c as x = foo(x) would be sugar for a.b. c = foo('a.b.c') and (a,*b, c) as x = foo(x) would be sugar for (a,*b, c) = foo('a, *b, c') - note my intentional inconsistent whitespace to demonstrate that whitespace ought to be normalised when generating the string representation.

Outer parens in tuple assignment would be required to make it clearly unambiguous; a, b as x would be a syntax error but might later (as a separate proposal) be allowed in order to let x be 'b' . I’m -0 on allowing this from the beginning; probably better to see how the general idea works out before adding in this complication.

I would prefer that this feature be limited to passing the string representation of some name to a function (or otherwise using it in an expression), as that’s an actually important use case (namedtuple, TypeVar). My dislike of using this for accessing the target object itself is pretty much what @AndersMunch has already explained: it’s far less confusing to just use a regular ol’ assignment for that.

“Python is not Perl” indeed!

IMO another good (also English-specific) mnemonic is “at rhymes with that”, and reading @ as “that” is a pretty natural way to speak the statement.

I suspect that I’m in the minority here but I personally found figuring out what assignment target means (i.e. whatever’s on the the left of the = operator) to be more confusing than mapping a punctuation character to the words assignment target . So perlish or not, to me eliminating @ isn’t really fixing anything.

TBH, in this version of the proposal you don’t get much for TypeVar . You are changing:

if you make up a name and copy it over you’re getting more verbosity than the original and still have repetition. Same for namedtuples. That’s whay I didn’t worry too much about the string representation when I covered this, I was more focused on Alyssa’s idea of avoiding re-evaluation of attribute accesses/slicing.

We have __set_name__ so descriptors know their own name. Have we thought of extending __set_name__ to work on objects? Or perhaps there is a reason why it’s not done? I think it would be neat if objects could capture the lhs as a name like in descriptors

(post deleted by author)

Allowing __target__ on the LFS would make the syntax ambiguous when there is also __target__ on the RHS:

Does __target__[:2] on the RHS become foo[:2] or foo[2:][:2] ?

Assignment to a name does not modify an object in-place. It merely sets the name on the LHS to a new reference to the object on the RHS. So __target__ = hex(v) would just set the local name v to a new object for that iteration rather than updating the entry in mydict , which will still hold a reference to the original value.

IMAGES

  1. Python Coding : Addition

    addition assignment operator in python

  2. How to Perform Addition in Python?

    addition assignment operator in python

  3. Python Operator

    addition assignment operator in python

  4. Arithmetic Operators In Python

    addition assignment operator in python

  5. Python Operators

    addition assignment operator in python

  6. Lesson 2

    addition assignment operator in python

VIDEO

  1. Assignment

  2. Assignment operator #operator #operator in python #python #code #datascience #pythonfullcourse

  3. Python Assignment Operator: Beginner's Guide by ByteAdmin

  4. python assignment operator

  5. Augmented assignment Operator

  6. program of assignment operators in C++

COMMENTS

  1. Python's Assignment Operator: Write Robust Assignments

    To create a new variable or to update the value of an existing one in Python, you'll use an assignment statement. This statement has the following three components: A left operand, which must be a variable. The assignment operator ( =) A right operand, which can be a concrete value, an object, or an expression.

  2. Assignment Operators in Python

    The Addition Assignment Operator is used to add the right-hand side operand with the left-hand side operand and then assigning the result to the left operand. Syntax: a += b. Example: ... Assignment operators in Python are used to assign values to variables. These operators can also perform additional operations during the assignment.

  3. += Addition Assignment

    Description ¶. Adds a value and the variable and assigns the result to that variable.

  4. Python Assignment Operators

    Python Assignment Operators. Assignment operators are used to assign values to variables: Operator. Example. Same As. Try it. =. x = 5. x = 5.

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

  6. The += Operator In Python

    In this lesson, we will look at the += operator in Python and see how it works with several simple examples. The operator '+=' is a shorthand for the addition assignment operator. It adds two values and assigns the sum to a variable (left operand). Let's look at three instances to have a better idea of how this operator works.

  7. Python Operators (With Examples)

    1. Python Arithmetic Operators. Arithmetic operators are used to perform mathematical operations like addition, subtraction, multiplication, etc. For example, sub = 10 - 5 # 5. Here, -is an arithmetic operator that subtracts two values or variables.

  8. A Guide to Python's += Operator

    The += operator is a pre-defined operator that adds two values and assigns the sum to a variable. For this reason, it's termed the "addition assignment" operator. The operator is typically used to store sums of numbers in counter variables to keep track of the frequency of repetitions of a specific operation.

  9. Operators

    Arithmetic operators are used in Python to perform basic arithmetic operations such as addition, subtraction, multiplication, division, and more. These operators are used on numeric data types such as integers, floats, and complex numbers. ... There are no specific "Logical Assignment Operators" in Python, as the logical operators and, or, ...

  10. Python Assignment Operators

    Introduction to Python Assignment Operators. ... 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. In [1]: a = 3 a += 2 print (a) 5 Subtraction and Assignment Operator.

  11. 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. Contents.

  12. python

    179. += adds another value with the variable's value and assigns the new value to the variable. -=, *=, /= does similar for subtraction, multiplication and division. Note that, as the currently most upvoted answer details, x += y is not the same thing as x = x + y, especially if x is a list.

  13. Arithmetic Operators in Python

    Dividing 6 by 3 using the / operator would result in 2.0 (always a float). Expression: 6 / 3. Floor division. Dividing 6 by 3 using the // operator would result in 2 (since 6 and 3 are integers). Expression: 6 // 3 Power. 6 to the power of 3 would result in 216. Expression: 6 ** 3. Modulo. 6 divided by 3 would result in a remainder of 0 ...

  14. Python Assignment Operators

    Operator Subtraction (-=) 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.

  15. Operators and Expressions in Python

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

  16. 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, ...

  17. Assignment Operators in Python

    Assignment Operators in Python are used to assign values to the variables. "=" is the fundamental Python assignment operator. They require two operands to operate upon. The left side operand is called a variable, and the right side operand is the value. The value on the right side of the "=" is assigned to the variable on the left side of "=".

  18. Python

    Python - Assignment Operators - 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. ... Python augmented assignment operators combines addition and assignment in one statement. Since Python supports mixed arithmetic, the two operands may ...

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

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

  21. Assignment Operator in Python

    The addition assignment operator is used to add a value to a variable and store the result in the same variable. The syntax for the addition assignment operator is: ... Q2 - Is it possible to chain assignment operators in Python? Ans - Yes, you can chain assignment operators in Python to perform multiple operations in one line of code. For ...

  22. Python Operators

    Operators in Python. This tutorial covers the different types of operators in Python, operator overloading, precedence and associativity. Just like in mathematics, programming languages like Python have operators. You can think of them as extremely simple functions that lie at the basis of computer science.

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

  24. Defining a symbolic syntax for referring to assignment targets

    __target_text__ could replace @'' for both identifier assignment and tuple assignment ( __target_name__ wouldn't match the latter use case) Sounds good indeed. With the name __target_text__ we wouldn't have to worry about a plural form. I doubt you could reasonably use that form to map function parameters to local variables of the same name ...