Python's Assignment Operator: Write Robust Assignments

Python's Assignment Operator: Write Robust Assignments

Table of Contents

The Assignment Statement Syntax

The assignment operator, assignments and variables, other assignment syntax, initializing and updating variables, making multiple variables refer to the same object, updating lists through indices and slices, adding and updating dictionary keys, doing parallel assignments, unpacking iterables, providing default argument values, augmented mathematical assignment operators, augmented assignments for concatenation and repetition, augmented bitwise assignment operators, annotated assignment statements, assignment expressions with the walrus operator, managed attribute assignments, define or call a function, work with classes, import modules and objects, use a decorator, access the control variable in a for loop or a comprehension, use the as keyword, access the _ special variable in an interactive session, built-in objects, named constants.

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

Learning about the Python assignment operator and its use for writing assignment statements will arm you with powerful tools for writing better and more robust Python code.

In this tutorial, you’ll:

  • Use Python’s assignment operator to write assignment statements
  • Take advantage of augmented assignments in Python
  • Explore assignment variants, like assignment expressions and managed attributes
  • Become aware of illegal and dangerous assignments in Python

You’ll dive deep into Python’s assignment statements. To get the most out of this tutorial, you should be comfortable with several basic topics, including variables , built-in data types , comprehensions , functions , and Python keywords . Before diving into some of the later sections, you should also be familiar with intermediate topics, such as object-oriented programming , constants , imports , type hints , properties , descriptors , and decorators .

Free Source Code: Click here to download the free assignment operator source code that you’ll use to write assignment statements that allow you to create, initialize, and update variables in your code.

Assignment Statements and the Assignment Operator

One of the most powerful programming language features is the ability to create, access, and mutate variables . In Python, a variable is a name that refers to a concrete value or object, allowing you to reuse that value or object throughout your code.

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

Here’s how an assignment statement will generally look in Python:

Here, variable represents a generic Python variable, while expression represents any Python object that you can provide as a concrete value—also known as a literal —or an expression that evaluates to a value.

To execute an assignment statement like the above, Python runs the following steps:

  • Evaluate the right-hand expression to produce a concrete value or object . This value will live at a specific memory address in your computer.
  • Store the object’s memory address in the left-hand variable . This step creates a new variable if the current one doesn’t already exist or updates the value of an existing variable.

The second step shows that variables work differently in Python than in other programming languages. In Python, variables aren’t containers for objects. Python variables point to a value or object through its memory address. They store memory addresses rather than objects.

This behavior difference directly impacts how data moves around in Python, which is always by reference . In most cases, this difference is irrelevant in your day-to-day coding, but it’s still good to know.

The central component of an assignment statement is the assignment operator . This operator is represented by the = symbol, which separates two operands:

  • A value or an expression that evaluates to a concrete value

Operators are special symbols that perform mathematical , logical , and bitwise operations in a programming language. The objects (or object) on which an operator operates are called operands .

Unary operators, like the not Boolean operator, operate on a single object or operand, while binary operators act on two. That means the assignment operator is a binary operator.

Note: Like C , Python uses == for equality comparisons and = for assignments. Unlike C, Python doesn’t allow you to accidentally use the assignment operator ( = ) in an equality comparison.

Equality is a symmetrical relationship, and assignment is not. For example, the expression a == 42 is equivalent to 42 == a . In contrast, the statement a = 42 is correct and legal, while 42 = a isn’t allowed. You’ll learn more about illegal assignments later on.

The right-hand operand in an assignment statement can be any Python object, such as a number , list , string , dictionary , or even a user-defined object. It can also be an expression. In the end, expressions always evaluate to concrete objects, which is their return value.

Here are a few examples of assignments in Python:

The first two sample assignments in this code snippet use concrete values, also known as literals , to create and initialize number and greeting . The third example assigns the result of a math expression to the total variable, while the last example uses a Boolean expression.

Note: You can use the built-in id() function to inspect the memory address stored in a given variable.

Here’s a short example of how this function works:

The number in your output represents the memory address stored in number . Through this address, Python can access the content of number , which is the integer 42 in this example.

If you run this code on your computer, then you’ll get a different memory address because this value varies from execution to execution and computer to computer.

Unlike expressions, assignment statements don’t have a return value because their purpose is to make the association between the variable and its value. That’s why the Python interpreter doesn’t issue any output in the above examples.

Now that you know the basics of how to write an assignment statement, it’s time to tackle why you would want to use one.

The assignment statement is the explicit way for you to associate a name with an object in Python. You can use this statement for two main purposes:

  • Creating and initializing new variables
  • Updating the values of existing variables

When you use a variable name as the left operand in an assignment statement for the first time, you’re creating a new variable. At the same time, you’re initializing the variable to point to the value of the right operand.

On the other hand, when you use an existing variable in a new assignment, you’re updating or mutating the variable’s value. Strictly speaking, every new assignment will make the variable refer to a new value and stop referring to the old one. Python will garbage-collect all the values that are no longer referenced by any existing variable.

Assignment statements not only assign a value to a variable but also determine the data type of the variable at hand. This additional behavior is another important detail to consider in this kind of statement.

Because Python is a dynamically typed language, successive assignments to a given variable can change the variable’s data type. Changing the data type of a variable during a program’s execution is considered bad practice and highly discouraged. It can lead to subtle bugs that can be difficult to track down.

Unlike in math equations, in Python assignments, the left operand must be a variable rather than an expression or a value. For example, the following construct is illegal, and Python flags it as invalid syntax:

In this example, you have expressions on both sides of the = sign, and this isn’t allowed in Python code. The error message suggests that you may be confusing the equality operator with the assignment one, but that’s not the case. You’re really running an invalid assignment.

To correct this construct and convert it into a valid assignment, you’ll have to do something like the following:

In this code snippet, you first import the sqrt() function from the math module. Then you isolate the hypotenuse variable in the original equation by using the sqrt() function. Now your code works correctly.

Now you know what kind of syntax is invalid. But don’t get the idea that assignment statements are rigid and inflexible. In fact, they offer lots of room for customization, as you’ll learn next.

Python’s assignment statements are pretty flexible and versatile. You can write them in several ways, depending on your specific needs and preferences. Here’s a quick summary of the main ways to write assignments in Python:

Up to this point, you’ve mostly learned about the base assignment syntax in the above code snippet. In the following sections, you’ll learn about multiple, parallel, and augmented assignments. You’ll also learn about assignments with iterable unpacking.

Read on to see the assignment statements in action!

Assignment Statements in Action

You’ll find and use assignment statements everywhere in your Python code. They’re a fundamental part of the language, providing an explicit way to create, initialize, and mutate variables.

You can use assignment statements with plain names, like number or counter . You can also use assignments in more complicated scenarios, such as with:

  • Qualified attribute names , like user.name
  • Indices and slices of mutable sequences, like a_list[i] and a_list[i:j]
  • Dictionary keys , like a_dict[key]

This list isn’t exhaustive. However, it gives you some idea of how flexible these statements are. You can even assign multiple values to an equal number of variables in a single line, commonly known as parallel assignment . Additionally, you can simultaneously assign the values in an iterable to a comma-separated group of variables in what’s known as an iterable unpacking operation.

In the following sections, you’ll dive deeper into all these topics and a few other exciting things that you can do with assignment statements in Python.

The most elementary use case of an assignment statement is to create a new variable and initialize it using a particular value or expression:

All these statements create new variables, assigning them initial values or expressions. For an initial value, you should always use the most sensible and least surprising value that you can think of. For example, initializing a counter to something different from 0 may be confusing and unexpected because counters almost always start having counted no objects.

Updating a variable’s current value or state is another common use case of assignment statements. In Python, assigning a new value to an existing variable doesn’t modify the variable’s current value. Instead, it causes the variable to refer to a different value. The previous value will be garbage-collected if no other variable refers to it.

Consider the following examples:

These examples run two consecutive assignments on the same variable. The first one assigns the string "Hello, World!" to a new variable named greeting .

The second assignment updates the value of greeting by reassigning it the "Hi, Pythonistas!" string. In this example, the original value of greeting —the "Hello, World!" string— is lost and garbage-collected. From this point on, you can’t access the old "Hello, World!" string.

Even though running multiple assignments on the same variable during a program’s execution is common practice, you should use this feature with caution. Changing the value of a variable can make your code difficult to read, understand, and debug. To comprehend the code fully, you’ll have to remember all the places where the variable was changed and the sequential order of those changes.

Because assignments also define the data type of their target variables, it’s also possible for your code to accidentally change the type of a given variable at runtime. A change like this can lead to breaking errors, like AttributeError exceptions. Remember that strings don’t have the same methods and attributes as lists or dictionaries, for example.

In Python, you can make several variables reference the same object in a multiple-assignment line. This can be useful when you want to initialize several similar variables using the same initial value:

In this example, you chain two assignment operators in a single line. This way, your two variables refer to the same initial value of 0 . Note how both variables hold the same memory address, so they point to the same instance of 0 .

When it comes to integer variables, Python exhibits a curious behavior. It provides a numeric interval where multiple assignments behave the same as independent assignments. Consider the following examples:

To create n and m , you use independent assignments. Therefore, they should point to different instances of the number 42 . However, both variables hold the same object, which you confirm by comparing their corresponding memory addresses.

Now check what happens when you use a greater initial value:

Now n and m hold different memory addresses, which means they point to different instances of the integer number 300 . In contrast, when you use multiple assignments, both variables refer to the same object. This tiny difference can save you small bits of memory if you frequently initialize integer variables in your code.

The implicit behavior of making independent assignments point to the same integer number is actually an optimization called interning . It consists of globally caching the most commonly used integer values in day-to-day programming.

Under the hood, Python defines a numeric interval in which interning takes place. That’s the interning interval for integer numbers. You can determine this interval using a small script like the following:

This script helps you determine the interning interval by comparing integer numbers from -10 to 500 . If you run the script from your command line, then you’ll get an output like the following:

This output means that if you use a single number between -5 and 256 to initialize several variables in independent statements, then all these variables will point to the same object, which will help you save small bits of memory in your code.

In contrast, if you use a number that falls outside of the interning interval, then your variables will point to different objects instead. Each of these objects will occupy a different memory spot.

You can use the assignment operator to mutate the value stored at a given index in a Python list. The operator also works with list slices . The syntax to write these types of assignment statements is the following:

In the first construct, expression can return any Python object, including another list. In the second construct, expression must return a series of values as a list, tuple, or any other sequence. You’ll get a TypeError if expression returns a single value.

Note: When creating slice objects, you can use up to three arguments. These arguments are start , stop , and step . They define the number that starts the slice, the number at which the slicing must stop retrieving values, and the step between values.

Here’s an example of updating an individual value in a list:

In this example, you update the value at index 2 using an assignment statement. The original number at that index was 7 , and after the assignment, the number is 3 .

Note: Using indices and the assignment operator to update a value in a tuple or a character in a string isn’t possible because tuples and strings are immutable data types in Python.

Their immutability means that you can’t change their items in place :

You can’t use the assignment operator to change individual items in tuples or strings. These data types are immutable and don’t support item assignments.

It’s important to note that you can’t add new values to a list by using indices that don’t exist in the target list:

In this example, you try to add a new value to the end of numbers by using an index that doesn’t exist. This assignment isn’t allowed because there’s no way to guarantee that new indices will be consecutive. If you ever want to add a single value to the end of a list, then use the .append() method.

If you want to update several consecutive values in a list, then you can use slicing and an assignment statement:

In the first example, you update the letters between indices 1 and 3 without including the letter at 3 . The second example updates the letters from index 3 until the end of the list. Note that this slicing appends a new value to the list because the target slice is shorter than the assigned values.

Also note that the new values were provided through a tuple, which means that this type of assignment allows you to use other types of sequences to update your target list.

The third example updates a single value using a slice where both indices are equal. In this example, the assignment inserts a new item into your target list.

In the final example, you use a step of 2 to replace alternating letters with their lowercase counterparts. This slicing starts at index 1 and runs through the whole list, stepping by two items each time.

Updating the value of an existing key or adding new key-value pairs to a dictionary is another common use case of assignment statements. To do these operations, you can use the following syntax:

The first construct helps you update the current value of an existing key, while the second construct allows you to add a new key-value pair to the dictionary.

For example, to update an existing key, you can do something like this:

In this example, you update the current inventory of oranges in your store using an assignment. The left operand is the existing dictionary key, and the right operand is the desired new value.

While you can’t add new values to a list by assignment, dictionaries do allow you to add new key-value pairs using the assignment operator. In the example below, you add a lemon key to inventory :

In this example, you successfully add a new key-value pair to your inventory with 100 units. This addition is possible because dictionaries don’t have consecutive indices but unique keys, which are safe to add by assignment.

The assignment statement does more than assign the result of a single expression to a single variable. It can also cope nicely with assigning multiple values to multiple variables simultaneously in what’s known as a parallel assignment .

Here’s the general syntax for parallel assignments in Python:

Note that the left side of the statement can be either a tuple or a list of variables. Remember that to create a tuple, you just need a series of comma-separated elements. In this case, these elements must be variables.

The right side of the statement must be a sequence or iterable of values or expressions. In any case, the number of elements in the right operand must match the number of variables on the left. Otherwise, you’ll get a ValueError exception.

In the following example, you compute the two solutions of a quadratic equation using a parallel assignment:

In this example, you first import sqrt() from the math module. Then you initialize the equation’s coefficients in a parallel assignment.

The equation’s solution is computed in another parallel assignment. The left operand contains a tuple of two variables, x1 and x2 . The right operand consists of a tuple of expressions that compute the solutions for the equation. Note how each result is assigned to each variable by position.

A classical use case of parallel assignment is to swap values between variables:

The highlighted line does the magic and swaps the values of previous_value and next_value at the same time. Note that in a programming language that doesn’t support this kind of assignment, you’d have to use a temporary variable to produce the same effect:

In this example, instead of using parallel assignment to swap values between variables, you use a new variable to temporarily store the value of previous_value to avoid losing its reference.

For a concrete example of when you’d need to swap values between variables, say you’re learning how to implement the bubble sort algorithm , and you come up with the following function:

In the highlighted line, you use a parallel assignment to swap values in place if the current value is less than the next value in the input list. To dive deeper into the bubble sort algorithm and into sorting algorithms in general, check out Sorting Algorithms in Python .

You can use assignment statements for iterable unpacking in Python. Unpacking an iterable means assigning its values to a series of variables one by one. The iterable must be the right operand in the assignment, while the variables must be the left operand.

Like in parallel assignments, the variables must come as a tuple or list. The number of variables must match the number of values in the iterable. Alternatively, you can use the unpacking operator ( * ) to grab several values in a variable if the number of variables doesn’t match the iterable length.

Here’s the general syntax for iterable unpacking in Python:

Iterable unpacking is a powerful feature that you can use all around your code. It can help you write more readable and concise code. For example, you may find yourself doing something like this:

Whenever you do something like this in your code, go ahead and replace it with a more readable iterable unpacking using a single and elegant assignment, like in the following code snippet:

The numbers list on the right side contains four values. The assignment operator unpacks these values into the four variables on the left side of the statement. The values in numbers get assigned to variables in the same order that they appear in the iterable. The assignment is done by position.

Note: Because Python sets are also iterables, you can use them in an iterable unpacking operation. However, it won’t be clear which value goes to which variable because sets are unordered data structures.

The above example shows the most common form of iterable unpacking in Python. The main condition for the example to work is that the number of variables matches the number of values in the iterable.

What if you don’t know the iterable length upfront? Will the unpacking work? It’ll work if you use the * operator to pack several values into one of your target variables.

For example, say that you want to unpack the first and second values in numbers into two different variables. Additionally, you would like to pack the rest of the values in a single variable conveniently called rest . In this case, you can use the unpacking operator like in the following code:

In this example, first and second hold the first and second values in numbers , respectively. These values are assigned by position. The * operator packs all the remaining values in the input iterable into rest .

The unpacking operator ( * ) can appear at any position in your series of target variables. However, you can only use one instance of the operator:

The iterable unpacking operator works in any position in your list of variables. Note that you can only use one unpacking operator per assignment. Using more than one unpacking operator isn’t allowed and raises a SyntaxError .

Dropping away unwanted values from the iterable is a common use case for the iterable unpacking operator. Consider the following example:

In Python, if you want to signal that a variable won’t be used, then you use an underscore ( _ ) as the variable’s name. In this example, useful holds the only value that you need to use from the input iterable. The _ variable is a placeholder that guarantees that the unpacking works correctly. You won’t use the values that end up in this disposable variable.

Note: In the example above, if your target iterable is a sequence data type, such as a list or tuple, then it’s best to access its last item directly.

To do this, you can use the -1 index:

Using -1 gives you access to the last item of any sequence data type. In contrast, if you’re dealing with iterators , then you won’t be able to use indices. That’s when the *_ syntax comes to your rescue.

The pattern used in the above example comes in handy when you have a function that returns multiple values, and you only need a few of these values in your code. The os.walk() function may provide a good example of this situation.

This function allows you to iterate over the content of a directory recursively. The function returns a generator object that yields three-item tuples. Each tuple contains the following items:

  • The path to the current directory as a string
  • The names of all the immediate subdirectories as a list of strings
  • The names of all the files in the current directory as a list of strings

Now say that you want to iterate over your home directory and list only the files. You can do something like this:

This code will issue a long output depending on the current content of your home directory. Note that you need to provide a string with the path to your user folder for the example to work. The _ placeholder variable will hold the unwanted data.

In contrast, the filenames variable will hold the list of files in the current directory, which is the data that you need. The code will print the list of filenames. Go ahead and give it a try!

The assignment operator also comes in handy when you need to provide default argument values in your functions and methods. Default argument values allow you to define functions that take arguments with sensible defaults. These defaults allow you to call the function with specific values or to simply rely on the defaults.

As an example, consider the following function:

This function takes one argument, called name . This argument has a sensible default value that’ll be used when you call the function without arguments. To provide this sensible default value, you use an assignment.

Note: According to PEP 8 , the style guide for Python code, you shouldn’t use spaces around the assignment operator when providing default argument values in function definitions.

Here’s how the function works:

If you don’t provide a name during the call to greet() , then the function uses the default value provided in the definition. If you provide a name, then the function uses it instead of the default one.

Up to this point, you’ve learned a lot about the Python assignment operator and how to use it for writing different types of assignment statements. In the following sections, you’ll dive into a great feature of assignment statements in Python. You’ll learn about augmented assignments .

Augmented Assignment Operators in Python

Python supports what are known as augmented assignments . An augmented assignment combines the assignment operator with another operator to make the statement more concise. Most Python math and bitwise operators have an augmented assignment variation that looks something like this:

Note that $ isn’t a valid Python operator. In this example, it’s a placeholder for a generic operator. This statement works as follows:

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

In practice, an augmented assignment like the above is equivalent to the following statement:

As you can conclude, augmented assignments are syntactic sugar . They provide a shorthand notation for a specific and popular kind of assignment.

For example, say that you need to define a counter variable to count some stuff in your code. You can use the += operator to increment counter by 1 using the following code:

In this example, the += operator, known as augmented addition , adds 1 to the previous value in counter each time you run the statement counter += 1 .

It’s important to note that unlike regular assignments, augmented assignments don’t create new variables. They only allow you to update existing variables. If you use an augmented assignment with an undefined variable, then you get a NameError :

Python evaluates the right side of the statement before assigning the resulting value back to the target variable. In this specific example, when Python tries to compute x + 1 , it finds that x isn’t defined.

Great! You now know that an augmented assignment consists of combining the assignment operator with another operator, like a math or bitwise operator. To continue this discussion, you’ll learn which math operators have an augmented variation in Python.

An equation like x = x + b doesn’t make sense in math. But in programming, a statement like x = x + b is perfectly valid and can be extremely useful. It adds b to x and reassigns the result back to x .

As you already learned, Python provides an operator to shorten x = x + b . Yes, the += operator allows you to write x += b instead. Python also offers augmented assignment operators for most math operators. Here’s a summary:

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

The Example column provides generic examples of how to use the operators in actual code. Note that x must be previously defined for the operators to work correctly. On the other hand, y can be either a concrete value or an expression that returns a value.

Note: The matrix multiplication operator ( @ ) doesn’t support augmented assignments yet.

Consider the following example of matrix multiplication using NumPy arrays:

Note that the exception traceback indicates that the operation isn’t supported yet.

To illustrate how augmented assignment operators work, say that you need to create a function that takes an iterable of numeric values and returns their sum. You can write this function like in the code below:

In this function, you first initialize total to 0 . In each iteration, the loop adds a new number to total using the augmented addition operator ( += ). When the loop terminates, total holds the sum of all the input numbers. Variables like total are known as accumulators . The += operator is typically used to update accumulators.

Note: Computing the sum of a series of numeric values is a common operation in programming. Python provides the built-in sum() function for this specific computation.

Another interesting example of using an augmented assignment is when you need to implement a countdown while loop to reverse an iterable. In this case, you can use the -= operator:

In this example, custom_reversed() is a generator function because it uses yield . Calling the function creates an iterator that yields items from the input iterable in reverse order. To decrement the control variable, index , you use an augmented subtraction statement that subtracts 1 from the variable in every iteration.

Note: Similar to summing the values in an iterable, reversing an iterable is also a common requirement. Python provides the built-in reversed() function for this specific computation, so you don’t have to implement your own. The above example only intends to show the -= operator in action.

Finally, counters are a special type of accumulators that allow you to count objects. Here’s an example of a letter counter:

To create this counter, you use a Python dictionary. The keys store the letters. The values store the counts. Again, to increment the counter, you use an augmented addition.

Counters are so common in programming that Python provides a tool specially designed to facilitate the task of counting. Check out Python’s Counter: The Pythonic Way to Count Objects for a complete guide on how to use this tool.

The += and *= augmented assignment operators also work with sequences , such as lists, tuples, and strings. The += operator performs augmented concatenations , while the *= operator performs augmented repetition .

These operators behave differently with mutable and immutable data types:

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

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

Consider the following examples and pay attention to the result of calling the id() function:

Mutable sequences like lists support the += augmented assignment operator through the .__iadd__() method, which performs an in-place addition. This method mutates the underlying list, appending new values to its end.

Note: If the left operand is mutable, then x += y may not be completely equivalent to x = x + y . For example, if you do list_1 = list_1 + list_2 instead of list_1 += list_2 above, then you’ll create a new list instead of mutating the existing one. This may be important if other variables refer to the same list.

Immutable sequences, such as tuples and strings, don’t provide an .__iadd__() method. Therefore, augmented concatenations fall back to the .__add__() method, which doesn’t modify the sequence in place but returns a new sequence.

There’s another difference between mutable and immutable sequences when you use them in an augmented concatenation. Consider the following examples:

With mutable sequences, the data to be concatenated can come as a list, tuple, string, or any other iterable. In contrast, with immutable sequences, the data can only come as objects of the same type. You can concatenate tuples to tuples and strings to strings, for example.

Again, the augmented repetition operator works with a sequence on the left side of the operator and an integer on the right side. This integer value represents the number of repetitions to get in the resulting sequence:

When the *= operator operates on a mutable sequence, it falls back to the .__imul__() method, which performs the operation in place, modifying the underlying sequence. In contrast, if *= operates on an immutable sequence, then .__mul__() is called, returning a new sequence of the same type.

Note: Values of n less than 0 are treated as 0 , which returns an empty sequence of the same data type as the target sequence on the left side of the *= operand.

Note that a_list[0] is a_list[3] returns True . This is because the *= operator doesn’t make a copy of the repeated data. It only reflects the data. This behavior can be a source of issues when you use the operator with mutable values.

For example, say that you want to create a list of lists to represent a matrix, and you need to initialize the list with n empty lists, like in the following code:

In this example, you use the *= operator to populate matrix with three empty lists. Now check out what happens when you try to populate the first sublist in matrix :

The appended values are reflected in the three sublists. This happens because the *= operator doesn’t make copies of the data that you want to repeat. It only reflects the data. Therefore, every sublist in matrix points to the same object and memory address.

If you ever need to initialize a list with a bunch of empty sublists, then use a list comprehension :

This time, when you populate the first sublist of matrix , your changes aren’t propagated to the other sublists. This is because all the sublists are different objects that live in different memory addresses.

Bitwise operators also have their augmented versions. The logic behind them is similar to that of the math operators. The following table summarizes the augmented bitwise operators that Python provides:

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

The augmented bitwise assignment operators perform the intended operation by taking the current value of the left operand as a starting point for the computation. Consider the following example, which uses the & and &= operators:

Programmers who work with high-level languages like Python rarely use bitwise operations in day-to-day coding. However, these types of operations can be useful in some situations.

For example, say that you’re implementing a Unix-style permission system for your users to access a given resource. In this case, you can use the characters "r" for reading, "w" for writing, and "x" for execution permissions, respectively. However, using bit-based permissions could be more memory efficient:

You can assign permissions to your users with the OR bitwise operator or the augmented OR bitwise operator. Finally, you can use the bitwise AND operator to check if a user has a certain permission, as you did in the final two examples.

You’ve learned a lot about augmented assignment operators and statements in this and the previous sections. These operators apply to math, concatenation, repetition, and bitwise operations. Now you’re ready to look at other assignment variants that you can use in your code or find in other developers’ code.

Other Assignment Variants

So far, you’ve learned that Python’s assignment statements and the assignment operator are present in many different scenarios and use cases. Those use cases include variable creation and initialization, parallel assignments, iterable unpacking, augmented assignments, and more.

In the following sections, you’ll learn about a few variants of assignment statements that can be useful in your future coding. You can also find these assignment variants in other developers’ code. So, you should be aware of them and know how they work in practice.

In short, you’ll learn about:

  • Annotated assignment statements with type hints
  • Assignment expressions with the walrus operator
  • Managed attribute assignments with properties and descriptors
  • Implicit assignments in Python

These topics will take you through several interesting and useful examples that showcase the power of Python’s assignment statements.

PEP 526 introduced a dedicated syntax for variable annotation back in Python 3.6 . The syntax consists of the variable name followed by a colon ( : ) and the variable type:

Even though these statements declare three variables with their corresponding data types, the variables aren’t actually created or initialized. So, for example, you can’t use any of these variables in an augmented assignment statement:

If you try to use one of the previously declared variables in an augmented assignment, then you get a NameError because the annotation syntax doesn’t define the variable. To actually define it, you need to use an assignment.

The good news is that you can use the variable annotation syntax in an assignment statement with the = operator:

The first statement in this example is what you can call an annotated assignment statement in Python. You may ask yourself why you should use type annotations in this type of assignment if everybody can see that counter holds an integer number. You’re right. In this example, the variable type is unambiguous.

However, imagine what would happen if you found a variable initialization like the following:

What would be the data type of each user in users ? If the initialization of users is far away from the definition of the User class, then there’s no quick way to answer this question. To clarify this ambiguity, you can provide the appropriate type hint for users :

Now you’re clearly communicating that users will hold a list of User instances. Using type hints in assignment statements that initialize variables to empty collection data types—such as lists, tuples, or dictionaries—allows you to provide more context about how your code works. This practice will make your code more explicit and less error-prone.

Up to this point, you’ve learned that regular assignment statements with the = operator don’t have a return value. They just create or update variables. Therefore, you can’t use a regular assignment to assign a value to a variable within the context of an expression.

Python 3.8 changed this by introducing a new type of assignment statement through PEP 572 . This new statement is known as an assignment expression or named expression .

Note: Expressions are a special type of statement in Python. Their distinguishing characteristic is that expressions always have a return value, which isn’t the case with all types of statements.

Unlike regular assignments, assignment expressions have a return value, which is why they’re called expressions in the first place. This return value is automatically assigned to a variable. To write an assignment expression, you must use the walrus operator ( := ), which was named for its resemblance to the eyes and tusks of a walrus lying on its side.

The general syntax of an assignment statement is as follows:

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

Assignment expressions come in handy when you want to reuse the result of an expression or part of an expression without using a dedicated assignment to grab this value beforehand.

Note: Assignment expressions with the walrus operator have several practical use cases. They also have a few restrictions. For example, they’re illegal in certain contexts, such as lambda functions, parallel assignments, and augmented assignments.

For a deep dive into this special type of assignment, check out The Walrus Operator: Python’s Assignment Expressions .

A particularly handy use case for assignment expressions is when you need to grab the result of an expression used in the context of a conditional statement. For example, say that you need to write a function to compute the mean of a sample of numeric values. Without the walrus operator, you could do something like this:

In this example, the sample size ( n ) is a value that you need to reuse in two different computations. First, you need to check whether the sample has data points or not. Then you need to use the sample size to compute the mean. To be able to reuse n , you wrote a dedicated assignment statement at the beginning of your function to grab the sample size.

You can avoid this extra step by combining it with the first use of the target value, len(sample) , using an assignment expression like the following:

The assignment expression introduced in the conditional computes the sample size and assigns it to n . This way, you guarantee that you have a reference to the sample size to use in further computations.

Because the assignment expression returns the sample size anyway, the conditional can check whether that size equals 0 or not and then take a certain course of action depending on the result of this check. The return statement computes the sample’s mean and sends the result back to the function caller.

Python provides a few tools that allow you to fine-tune the operations behind the assignment of attributes. The attributes that run implicit operations on assignments are commonly referred to as managed attributes .

Properties are the most commonly used tool for providing managed attributes in your classes. However, you can also use descriptors and, in some cases, the .__setitem__() special method.

To understand what fine-tuning the operation behind an assignment means, say that you need a Point class that only allows numeric values for its coordinates, x and y . To write this class, you must set up a validation mechanism to reject non-numeric values. You can use properties to attach the validation functionality on top of x and y .

Here’s how you can write your class:

In Point , you use properties for the .x and .y coordinates. Each property has a getter and a setter method . The getter method returns the attribute at hand. The setter method runs the input validation using a try … except block and the built-in float() function. Then the method assigns the result to the actual attribute.

Here’s how your class works in practice:

When you use a property-based attribute as the left operand in an assignment statement, Python automatically calls the property’s setter method, running any computation from it.

Because both .x and .y are properties, the input validation runs whenever you assign a value to either attribute. In the first example, the input values are valid numbers and the validation passes. In the final example, "one" isn’t a valid numeric value, so the validation fails.

If you look at your Point class, you’ll note that it follows a repetitive pattern, with the getter and setter methods looking quite similar. To avoid this repetition, you can use a descriptor instead of a property.

A descriptor is a class that implements the descriptor protocol , which consists of four special methods :

  • .__get__() runs when you access the attribute represented by the descriptor.
  • .__set__() runs when you use the attribute in an assignment statement.
  • .__delete__() runs when you use the attribute in a del statement.
  • .__set_name__() sets the attribute’s name, creating a name-aware attribute.

Here’s how your code may look if you use a descriptor to represent the coordinates of your Point class:

You’ve removed repetitive code by defining Coordinate as a descriptor that manages the input validation in a single place. Go ahead and run the following code to try out the new implementation of Point :

Great! The class works as expected. Thanks to the Coordinate descriptor, you now have a more concise and non-repetitive version of your original code.

Another way to fine-tune the operations behind an assignment statement is to provide a custom implementation of .__setitem__() in your class. You’ll use this method in classes representing mutable data collections, such as custom list-like or dictionary-like classes.

As an example, say that you need to create a dictionary-like class that stores its keys in lowercase letters:

In this example, you create a dictionary-like class by subclassing UserDict from collections . Your class implements a .__setitem__() method, which takes key and value as arguments. The method uses str.lower() to convert key into lowercase letters before storing it in the underlying dictionary.

Python implicitly calls .__setitem__() every time you use a key as the left operand in an assignment statement. This behavior allows you to tweak how you process the assignment of keys in your custom dictionary.

Implicit Assignments in Python

Python implicitly runs assignments in many different contexts. In most cases, these implicit assignments are part of the language syntax. In other cases, they support specific behaviors.

Whenever you complete an action in the following list, Python runs an implicit assignment for you:

  • Define or call a function
  • Define or instantiate a class
  • Use the current instance , self
  • Import modules and objects
  • Use a decorator
  • Use the control variable in a for loop or a comprehension
  • Use the as qualifier in with statements , imports, and try … except blocks
  • Access the _ special variable in an interactive session

Behind the scenes, Python performs an assignment in every one of the above situations. In the following subsections, you’ll take a tour of all these situations.

When you define a function, the def keyword implicitly assigns a function object to your function’s name. Here’s an example:

From this point on, the name greet refers to a function object that lives at a given memory address in your computer. You can call the function using its name and a pair of parentheses with appropriate arguments. This way, you can reuse greet() wherever you need it.

If you call your greet() function with fellow as an argument, then Python implicitly assigns the input argument value to the name parameter on the function’s definition. The parameter will hold a reference to the input arguments.

When you define a class with the class keyword, you’re assigning a specific name to a class object . You can later use this name to create instances of that class. Consider the following example:

In this example, the name User holds a reference to a class object, which was defined in __main__.User . Like with a function, when you call the class’s constructor with the appropriate arguments to create an instance, Python assigns the arguments to the parameters defined in the class initializer .

Another example of implicit assignments is the current instance of a class, which in Python is called self by convention. This name implicitly gets a reference to the current object whenever you instantiate a class. Thanks to this implicit assignment, you can access .name and .job from within the class without getting a NameError in your code.

Import statements are another variant of implicit assignments in Python. Through an import statement, you assign a name to a module object, class, function, or any other imported object. This name is then created in your current namespace so that you can access it later in your code:

In this example, you import the sys module object from the standard library and assign it to the sys name, which is now available in your namespace, as you can conclude from the second call to the built-in dir() function.

You also run an implicit assignment when you use a decorator in your code. The decorator syntax is just a shortcut for a formal assignment like the following:

Here, you call decorator() with a function object as an argument. This call will typically add functionality on top of the existing function, func() , and return a function object, which is then reassigned to the func name.

The decorator syntax is syntactic sugar for replacing the previous assignment, which you can now write as follows:

Even though this new code looks pretty different from the above assignment, the code implicitly runs the same steps.

Another situation in which Python automatically runs an implicit assignment is when you use a for loop or a comprehension. In both cases, you can have one or more control variables that you then use in the loop or comprehension body:

The memory address of control_variable changes on each iteration of the loop. This is because Python internally reassigns a new value from the loop iterable to the loop control variable on each cycle.

The same behavior appears in comprehensions:

In the end, comprehensions work like for loops but use a more concise syntax. This comprehension creates a new list of strings that mimic the output from the previous example.

The as keyword in with statements, except clauses, and import statements is another example of an implicit assignment in Python. This time, the assignment isn’t completely implicit because the as keyword provides an explicit way to define the target variable.

In a with statement, the target variable that follows the as keyword will hold a reference to the context manager that you’re working with. As an example, say that you have a hello.txt file with the following content:

You want to open this file and print each of its lines on your screen. In this case, you can use the with statement to open the file using the built-in open() function.

In the example below, you accomplish this. You also add some calls to print() that display information about the target variable defined by the as keyword:

This with statement uses the open() function to open hello.txt . The open() function is a context manager that returns a text file object represented by an io.TextIOWrapper instance.

Since you’ve defined a hello target variable with the as keyword, now that variable holds a reference to the file object itself. You confirm this by printing the object and its memory address. Finally, the for loop iterates over the lines and prints this content to the screen.

When it comes to using the as keyword in the context of an except clause, the target variable will contain an exception object if any exception occurs:

In this example, you run a division that raises a ZeroDivisionError . The as keyword assigns the raised exception to error . Note that when you print the exception object, you get only the message because exceptions have a custom .__str__() method that supports this behavior.

There’s a final detail to remember when using the as specifier in a try … except block like the one in the above example. Once you leave the except block, the target variable goes out of scope , and you can’t use it anymore.

Finally, Python’s import statements also support the as keyword. In this context, you can use as to import objects with a different name:

In these examples, you use the as keyword to import the numpy package with the np name and pandas with the name pd . If you call dir() , then you’ll realize that np and pd are now in your namespace. However, the numpy and pandas names are not.

Using the as keyword in your imports comes in handy when you want to use shorter names for your objects or when you need to use different objects that originally had the same name in your code. It’s also useful when you want to make your imported names non-public using a leading underscore, like in import sys as _sys .

The final implicit assignment that you’ll learn about in this tutorial only occurs when you’re using Python in an interactive session. Every time you run a statement that returns a value, the interpreter stores the result in a special variable denoted by a single underscore character ( _ ).

You can access this special variable as you’d access any other variable:

These examples cover several situations in which Python internally uses the _ variable. The first two examples evaluate expressions. Expressions always have a return value, which is automatically assigned to the _ variable every time.

When it comes to function calls, note that if your function returns a fruitful value, then _ will hold it. In contrast, if your function returns None , then the _ variable will remain untouched.

The next example consists of a regular assignment statement. As you already know, regular assignments don’t return any value, so the _ variable isn’t updated after these statements run. Finally, note that accessing a variable in an interactive session returns the value stored in the target variable. This value is then assigned to the _ variable.

Note that since _ is a regular variable, you can use it in other expressions:

In this example, you first create a list of values. Then you call len() to get the number of values in the list. Python automatically stores this value in the _ variable. Finally, you use _ to compute the mean of your list of values.

Now that you’ve learned about some of the implicit assignments that Python runs under the hood, it’s time to dig into a final assignment-related topic. In the following few sections, you’ll learn about some illegal and dangerous assignments that you should be aware of and avoid in your code.

Illegal and Dangerous Assignments in Python

In Python, you’ll find a few situations in which using assignments is either forbidden or dangerous. You must be aware of these special situations and try to avoid them in your code.

In the following sections, you’ll learn when using assignment statements isn’t allowed in Python. You’ll also learn about some situations in which using assignments should be avoided if you want to keep your code consistent and robust.

You can’t use Python keywords as variable names in assignment statements. This kind of assignment is explicitly forbidden. If you try to use a keyword as a variable name in an assignment, then you get a SyntaxError :

Whenever you try to use a keyword as the left operand in an assignment statement, you get a SyntaxError . Keywords are an intrinsic part of the language and can’t be overridden.

If you ever feel the need to name one of your variables using a Python keyword, then you can append an underscore to the name of your variable:

In this example, you’re using the desired name for your variables. Because you added a final underscore to the names, Python doesn’t recognize them as keywords, so it doesn’t raise an error.

Note: Even though adding an underscore at the end of a name is an officially recommended practice , it can be confusing sometimes. Therefore, try to find an alternative name or use a synonym whenever you find yourself using this convention.

For example, you can write something like this:

In this example, using the name booking_class for your variable is way clearer and more descriptive than using class_ .

You’ll also find that you can use only a few keywords as part of the right operand in an assignment statement. Those keywords will generally define simple statements that return a value or object. These include lambda , and , or , not , True , False , None , in , and is . You can also use the for keyword when it’s part of a comprehension and the if keyword when it’s used as part of a ternary operator .

In an assignment, you can never use a compound statement as the right operand. Compound statements are those that require an indented block, such as for and while loops, conditionals, with statements, try … except blocks, and class or function definitions.

Sometimes, you need to name variables, but the desired or ideal name is already taken and used as a built-in name. If this is your case, think harder and find another name. Don’t shadow the built-in.

Shadowing built-in names can cause hard-to-identify problems in your code. A common example of this issue is using list or dict to name user-defined variables. In this case, you override the corresponding built-in names, which won’t work as expected if you use them later in your code.

Consider the following example:

The exception in this example may sound surprising. How come you can’t use list() to build a list from a call to map() that returns a generator of square numbers?

By using the name list to identify your list of numbers, you shadowed the built-in list name. Now that name points to a list object rather than the built-in class. List objects aren’t callable, so your code no longer works.

In Python, you’ll have nothing that warns against using built-in, standard-library, or even relevant third-party names to identify your own variables. Therefore, you should keep an eye out for this practice. It can be a source of hard-to-debug errors.

In programming, a constant refers to a name associated with a value that never changes during a program’s execution. Unlike other programming languages, Python doesn’t have a dedicated syntax for defining constants. This fact implies that Python doesn’t have constants in the strict sense of the word.

Python only has variables. If you need a constant in Python, then you’ll have to define a variable and guarantee that it won’t change during your code’s execution. To do that, you must avoid using that variable as the left operand in an assignment statement.

To tell other Python programmers that a given variable should be treated as a constant, you must write your variable’s name in capital letters with underscores separating the words. This naming convention has been adopted by the Python community and is a recommendation that you’ll find in the Constants section of PEP 8 .

In the following examples, you define some constants in Python:

The problem with these constants is that they’re actually variables. Nothing prevents you from changing their value during your code’s execution. So, at any time, you can do something like the following:

These assignments modify the value of two of your original constants. Python doesn’t complain about these changes, which can cause issues later in your code. As a Python developer, you must guarantee that named constants in your code remain constant.

The only way to do that is never to use named constants in an assignment statement other than the constant definition.

You’ve learned a lot about Python’s assignment operators and how to use them for writing assignment statements . With this type of statement, you can create, initialize, and update variables according to your needs. Now you have the required skills to fully manage the creation and mutation of variables in your Python code.

In this tutorial, you’ve learned how to:

  • Write assignment statements using Python’s assignment operators
  • Work with augmented assignments in Python
  • Explore assignment variants, like assignment expression and managed attributes
  • Identify illegal and dangerous assignments in Python

Learning about the Python assignment operator and how to use it in assignment statements is a fundamental skill in Python. It empowers you to write reliable and effective Python code.

🐍 Python Tricks 💌

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

Python Tricks Dictionary Merge

About Leodanis Pozo Ramos

Leodanis Pozo Ramos

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

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

Aldren Santos

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

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

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

What Do You Think?

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

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

Keep Learning

Related Topics: intermediate best-practices python

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

Already have an account? Sign-In

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

Python's Assignment Operator: Write Robust Assignments (Source Code)

🔒 No spam. We take your privacy seriously.

why is assignment operator important

Home » Learn C Programming from Scratch » C Assignment Operators

C Assignment Operators

Summary : in this tutorial, you’ll learn about the C assignment operators and how to use them effectively.

Introduction to the C assignment operators

An assignment operator assigns the vale of the right-hand operand to the left-hand operand. The following example uses the assignment operator (=) to assign 1 to the counter variable:

After the assignmment, the counter variable holds the number 1.

The following example adds 1 to the counter and assign the result to the counter:

The = assignment operator is called a simple assignment operator. It assigns the value of the left operand to the right operand.

Besides the simple assignment operator, C supports compound assignment operators. A compound assignment operator performs the operation specified by the additional operator and then assigns the result to the left operand.

The following example uses a compound-assignment operator (+=):

The expression:

is equivalent to the following expression:

The following table illustrates the compound-assignment operators in C:

OperatorOperation PerformedExampleEquivalent expression
Multiplication assignmentx *= yx = x * y
Division assignmentx /= yx = x / y
Remainder assignmentx %= yx = x % y
Addition assignmentx += yx = x + y
Subtraction assignmentx -= yx = x – y
Left-shift assignmentx <<= yx = x <<=y
Right-shift assignmentx >>=yx = x >>= y
Bitwise-AND assignmentx &= yx = x & y
Bitwise-exclusive-OR assignmentx ^= yx = x ^ y
Bitwise-inclusive-OR assignmentx |= yx = x | y
  • A simple assignment operator assigns the value of the left operand to the right operand.
  • A compound assignment operator performs the operation specified by the additional operator and then assigns the result to the left operand.

01 Career Opportunities

02 beginner, 03 intermediate, 04 advanced, 05 training programs, c programming assignment operators, free c programming online course with certificate, what is an assignment operator in c, types of assignment operators in c.

1. Simple Assignment Operator (=)

Example of simple assignment operator.

2. Compound Assignment Operators

+=addition assignmentIt adds the right operand to the left operand and assigns the result to the left operand.
-=subtraction assignmentIt subtracts the right operand from the left operand and assigns the result to the left operand.
*=multiplication assignmentIt multiplies the right operand with the left operand and assigns the result to the left operand
/=division assignmentIt divides the left operand with the right operand and assigns the result to the left operand.
%=modulo assignmentIt takes modulus using two operands and assigns the result to the left operand.

Example of Augmented Arithmetic and Assignment Operators

&=bitwise AND assignmentIt performs the bitwise AND operation on the variable with the value on the right
|=bitwise OR assignmentIt performs the bitwise OR operation on the variable with the value on the right
^=bitwise XOR assignmentIt performs the bitwise XOR operation on the variable with the value on the right
<<=bitwise left shift assignmentShifts the bits of the variable to the left by the value on the right
>>=bitwise right shift assignmentShifts the bits of the variable to the right by the value on the right

Example of Augmented Bitwise and Assignment Operators

Practice problems on assignment operators in c, 1. what will the value of "x" be after the execution of the following code, 2. after executing the following code, what is the value of the number variable, benefits of using assignment operators, best practices and tips for using the assignment operator, live classes schedule.

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

About Author

cppreference.com

Assignment operators.

(C++20)
(C++20)
(C++11)
(C++20)
(C++17)
(C++11)
(C++11)
General topics
(C++11)
-
-expression
block


/
(C++11)
(C++11)
(C++11)
(C++20)
(C++20)
(C++11)

expression
pointer
specifier

specifier (C++11)
specifier (C++11)
(C++11)

(C++11)
(C++11)
(C++11)
General
(C++11)
(C++20)
(C++26)
(C++11)
(C++11)
-expression
-expression
-expression
(C++11)
(C++11)
(C++17)
(C++20)
    

Assignment operators modify the value of the object.

Operator name  Syntax  Prototype examples (for class T)
Inside class definition Outside class definition
simple assignment Yes T& T::operator =(const T2& b);
addition assignment Yes T& T::operator +=(const T2& b); T& operator +=(T& a, const T2& b);
subtraction assignment Yes T& T::operator -=(const T2& b); T& operator -=(T& a, const T2& b);
multiplication assignment Yes T& T::operator *=(const T2& b); T& operator *=(T& a, const T2& b);
division assignment Yes T& T::operator /=(const T2& b); T& operator /=(T& a, const T2& b);
remainder assignment Yes T& T::operator %=(const T2& b); T& operator %=(T& a, const T2& b);
bitwise AND assignment Yes T& T::operator &=(const T2& b); T& operator &=(T& a, const T2& b);
bitwise OR assignment Yes T& T::operator |=(const T2& b); T& operator |=(T& a, const T2& b);
bitwise XOR assignment Yes T& T::operator ^=(const T2& b); T& operator ^=(T& a, const T2& b);
bitwise left shift assignment Yes T& T::operator <<=(const T2& b); T& operator <<=(T& a, const T2& b);
bitwise right shift assignment Yes T& T::operator >>=(const T2& b); T& operator >>=(T& a, const T2& b);

this, and most also return *this so that the user-defined operators can be used in the same manner as the built-ins. However, in a user-defined operator overload, any type can be used as return type (including void). can be any type including .
Definitions Assignment operator syntax Built-in simple assignment operator Assignment from an expression Assignment from a non-expression initializer clause Built-in compound assignment operator Example Defect reports See also

[ edit ] Definitions

Copy assignment replaces the contents of the object a with a copy of the contents of b ( b is not modified). For class types, this is performed in a special member function, described in copy assignment operator .

replaces the contents of the object a with the contents of b, avoiding copying if possible (b may be modified). For class types, this is performed in a special member function, described in .

(since C++11)

For non-class types, copy and move assignment are indistinguishable and are referred to as direct assignment .

Compound assignment replace the contents of the object a with the result of a binary operation between the previous value of a and the value of b .

[ edit ] Assignment operator syntax

The assignment expressions have the form

target-expr new-value (1)
target-expr op new-value (2)
target-expr - the expression to be assigned to
op - one of *=, /= %=, += -=, <<=, >>=, &=, ^=, |=
new-value - the expression (until C++11) (since C++11) to assign to the target
  • ↑ target-expr must have higher precedence than an assignment expression.
  • ↑ new-value cannot be a comma expression, because its precedence is lower.

If new-value is not an expression, the assignment expression will never match an overloaded compound assignment operator.

(since C++11)

[ edit ] Built-in simple assignment operator

For the built-in simple assignment, the object referred to by target-expr is modified by replacing its value with the result of new-value . target-expr must be a modifiable lvalue.

The result of a built-in simple assignment is an lvalue of the type of target-expr , referring to target-expr . If target-expr is a bit-field , the result is also a bit-field.

[ edit ] Assignment from an expression

If new-value is an expression, it is implicitly converted to the cv-unqualified type of target-expr . When target-expr is a bit-field that cannot represent the value of the expression, the resulting value of the bit-field is implementation-defined.

If target-expr and new-value identify overlapping objects, the behavior is undefined (unless the overlap is exact and the type is the same).

If the type of target-expr is volatile-qualified, the assignment is deprecated, unless the (possibly parenthesized) assignment expression is a or an .

(since C++20)

new-value is only allowed not to be an expression in following situations:

is of a , and new-value is empty or has only one element. In this case, given an invented variable t declared and initialized as T t = new-value , the meaning of x = new-value  is x = t. is of class type. In this case, new-value is passed as the argument to the assignment operator function selected by .   <double> z; z = {1, 2}; // meaning z.operator=({1, 2}) z += {1, 2}; // meaning z.operator+=({1, 2})   int a, b; a = b = {1}; // meaning a = b = 1; a = {1} = b; // syntax error
(since C++11)

In overload resolution against user-defined operators , for every type T , the following function signatures participate in overload resolution:

& operator=(T*&, T*);
volatile & operator=(T*volatile &, T*);

For every enumeration or pointer to member type T , optionally volatile-qualified, the following function signature participates in overload resolution:

operator=(T&, T);

For every pair A1 and A2 , where A1 is an arithmetic type (optionally volatile-qualified) and A2 is a promoted arithmetic type, the following function signature participates in overload resolution:

operator=(A1&, A2);

[ edit ] Built-in compound assignment operator

The behavior of every built-in compound-assignment expression target-expr   op   =   new-value is exactly the same as the behavior of the expression target-expr   =   target-expr   op   new-value , except that target-expr is evaluated only once.

The requirements on target-expr and new-value of built-in simple assignment operators also apply. Furthermore:

  • For + = and - = , the type of target-expr must be an arithmetic type or a pointer to a (possibly cv-qualified) completely-defined object type .
  • For all other compound assignment operators, the type of target-expr must be an arithmetic type.

In overload resolution against user-defined operators , for every pair A1 and A2 , where A1 is an arithmetic type (optionally volatile-qualified) and A2 is a promoted arithmetic type, the following function signatures participate in overload resolution:

operator*=(A1&, A2);
operator/=(A1&, A2);
operator+=(A1&, A2);
operator-=(A1&, A2);

For every pair I1 and I2 , where I1 is an integral type (optionally volatile-qualified) and I2 is a promoted integral type, the following function signatures participate in overload resolution:

operator%=(I1&, I2);
operator<<=(I1&, I2);
operator>>=(I1&, I2);
operator&=(I1&, I2);
operator^=(I1&, I2);
operator|=(I1&, I2);

For every optionally cv-qualified object type T , the following function signatures participate in overload resolution:

& operator+=(T*&, );
& operator-=(T*&, );
volatile & operator+=(T*volatile &, );
volatile & operator-=(T*volatile &, );

[ edit ] Example

Possible output:

[ edit ] Defect reports

The following behavior-changing defect reports were applied retroactively to previously published C++ standards.

DR Applied to Behavior as published Correct behavior
C++11 for assignments to class type objects, the right operand
could be an initializer list only when the assignment
is defined by a user-defined assignment operator
removed user-defined
assignment constraint
C++11 E1 = {E2} was equivalent to E1 = T(E2)
( is the type of ), this introduced a C-style cast
it is equivalent
to E1 = T{E2}
C++20 compound assignment operators for volatile
-qualified types were inconsistently deprecated
none of them
is deprecated
C++11 an assignment from a non-expression initializer clause
to a scalar value would perform direct-list-initialization
performs copy-list-
initialization instead
C++20 bitwise compound assignment operators for volatile types
were deprecated while being useful for some platforms
they are not
deprecated

[ edit ] See also

Operator precedence

Operator overloading

Common operators

a = b
a += b
a -= b
a *= b
a /= b
a %= b
a &= b
a |= b
a ^= b
a <<= b
a >>= b

++a
--a
a++
a--

+a
-a
a + b
a - b
a * b
a / b
a % b
~a
a & b
a | b
a ^ b
a << b
a >> b

!a
a && b
a || b

a == b
a != b
a < b
a > b
a <= b
a >= b
a <=> b

a[...]
*a
&a
a->b
a.b
a->*b
a.*b

function call
a(...)
comma
a, b
conditional
a ? b : c
Special operators

converts one type to another related type
converts within inheritance hierarchies
adds or removes -qualifiers
converts type to unrelated type
converts one type to another by a mix of , , and
creates objects with dynamic storage duration
destructs objects previously created by the new expression and releases obtained memory area
queries the size of a type
queries the size of a (since C++11)
queries the type information of a type
checks if an expression can throw an exception (since C++11)
queries alignment requirements of a type (since C++11)

for Assignment operators
  • Recent changes
  • Offline version
  • What links here
  • Related changes
  • Upload file
  • Special pages
  • Printable version
  • Permanent link
  • Page information
  • In other languages
  • This page was last modified on 25 January 2024, at 23:41.
  • Privacy policy
  • About cppreference.com
  • Disclaimers

Powered by MediaWiki

  • All Courses
  • Free Courses
  • Machine Learning with Python
  • Programming
  • Python for Educators
  • Unreal Engine
  • Best Game Engines – Which Should You Use?
  • Unity vs Unreal
  • Unity vs Godot
  • Unreal vs Godot
  • GameMaker vs Unity
  • Construct vs GameMaker
  • Best Game Development Courses (Full List)
  • Programming Language for Games
  • How to Make a Game
  • What is Unreal Engine?
  • How to Make a VR Game
  • How to Make an HTML5 Game
  • What is Phaser?
  • Roblox Game Making Tutorials
  • What is Unity?
  • How to Make a Unity Game?
  • How to Make a Mobile Game in Unity
  • Unity Multiplayer Tutorial
  • Unity RPG Tutorial
  • Unity Animator Tutorial
  • Unity Certification
  • Unity Platformer Tutorial
  • Procedural Generation
  • What is Godot?
  • Best Godot Online Courses
  • Best Godot Tutorials
  • Complete Guide to GDScript
  • Godot RPG Tutorial
  • Godot Collision Detection
  • What is Python Programming?
  • How to Learn Python?
  • Best Python Courses – Complete List
  • Complete Guide to Python Enums
  • Generative AI in Python
  • Python Turtle Tutorial
  • Why Learn Coding?
  • What is Programming?
  • How to Learn Coding for Free
  • The Best Way to Learn to Code – 10 Steps
  • Beginners Coding Success Guide
  • Code Editor Comparison
  • How to Code a Game
  • Complete Guide to C#
  • Create Free Account

aa What Are Assignment Operators Complete Guide - What Are Assignment Operators - Complete Guide

What Are Assignment Operators – Complete Guide

Understanding the role of assignment operators in programming is like learning how to pass the baton in a relay race; it’s about transferring values into variables effectively and accurately. These operators are the bread and butter of programming languages, allowing you to store and update data as your code runs. Whether you’re new to coding or brushing up on your programming skills, grasping assignment operators is a must for writing efficient and effective code. Dive into this tutorial to unlock the full potential of manipulating data in your programs!

Table of contents

What Are Assignment Operators?

Assignment operators are a staple in the world of programming, serving as the means to assign values to variables. They are the equals signs and plus-equals equations that usher data into placeholders, ready to be manipulated and presented as needed.

What Are They Used For?

These operators enable us to store values, update information on the fly, and maintain state within our programs. Without them, our code would be static and unresponsive – they are the dynamic force behind variable assignment and updating.

Why Should I Learn About Assignment Operators?

Learning about assignment operators is foundational to programming. They allow us to:

– Initiate and change variable values. – Create interactive and responsive programs. – Write more concise and readable code.

CTA Small Image - What Are Assignment Operators - Complete Guide

Basic Assignment Operator

The most common assignment operator is the simple equals sign (=), which assigns the value on its right to the variable on its left. Here’s a straightforward example:

This operator is used to initialize variables, and it can also be used to reassign new values to existing variables:

Adding and Assigning

Often, you’ll want to increase a variable’s value by a certain amount. This is where the addition assignment operator (+=) comes in:

It saves you from having to write the variable name twice, streamlining your code and making it easier to read.

Subtracting and Assigning

Just like with addition, you might want to decrease a variable’s value. The subtraction assignment operator (-=) reduces a variable by the number on its right:

Multiplication and Assignment

When you need to multiply a variable by a value and reassign the product back to the variable, you can use the multiplication assignment operator (*=):

This operator helps maintain clean code instead of using longer statements that can get cluttered quickly if you’re performing many calculations.

Division and Assignment

The division assignment operator (/=) divides a variable by a number and assigns the result to that variable:

Using this operator can simplify your code significantly, especially in cases where you need to perform successive divisions on the same variable.

Modulus and Assignment

Finally, there’s the modulus assignment operator (%=), which assigns the remainder of the division to the variable:

The modulus operator is particularly useful in algorithms where you need to find out if a number is even or odd or fit a value into a particular range.

Mastering these operators is like getting the keys to the kingdom of efficient and maintainable code. With these examples under your belt, you have taken a big step towards becoming a more proficient programmer. In the next section, we’ll explore some other assignment operators that are used less frequently but are just as important.

After mastering the basics, let’s dive into some more assignment operators that can further enhance your coding prowess. These may not be used as frequently, but they’re important for writing concise code and can be a real-time saver in many situations.

Exponentiation and Assignment : When you want to raise a variable to the power of a certain number, you could use the Math.pow method or simply use the exponentiation assignment operator (**=) to keep your code neater:

It’s a handy operator for mathematical calculations, especially when you’re dealing with exponential growth or compound interest calculations.

Bitwise Operators and Assignment : Bitwise assignment operators like <>=, and &= are a bit more niche, used for manipulating bits within binary representations of numbers:

These operators are largely used in low-level programming, graphics, cryptography, and where performance optimization is critical.

Logical AND (&&=) and OR (||=) Assignment : In the realm of JavaScript, ES2021 introduced logical assignment operators that combine logical operations with assignment. Here are some examples:

The ||= operator assigns the value on its right side to the variable if the variable is currently null, undefined, or false. The &&= operator does the opposite, updating the variable if it’s already truthy.

Nullish Coalescing Assignment (??=) Operator : Introduced along with the logical assignment operators, the nullish coalescing assignment operator (??=) only assigns a value to a variable if that variable is currently null or undefined—not merely falsy like the || operator:

This operator is particularly useful when you want to ensure that variables have default values without overriding falsy but valid values like 0 or an empty string.

Understanding and utilizing these operators can lead to cleaner, more efficient, and more readable code, a critical factor in program maintenance and development. Our journey through assignment operators has shown us that, while some might seem complex at first glance, they’re all designed to make a programmer’s life easier. Remember that as with all programming concepts, practice is key to getting comfortable with these tools, so feel free to use this guide as a starting block for your exploration.

Understanding the behavior of assignment operators in edge cases can deepen your knowledge and help you to write better, more predictable code. Let’s examine some more practical examples, exploring how you can leverage these operators in less straightforward situations.

Consider how the += operator works with strings. It’s commonly used to concatenate strings effectively:

Now, let’s mix data types. When you add a number to a string, JavaScript converts the number to a string before concatenation:

Moving on to bitwise operators with more practical examples, let’s manipulate RGBA color values, which are often represented by 32-bit integers:

Bitwise operators are not limited to numbers. You can use them to toggle booleans or conditionally reset values:

Logical operators can help you write more concise conditional assignments. Consider setting default function parameters:

Even more nuanced is the nullish coalescing operator in conjunction with the Optional Chaining operator (?.) . This union elegantly handles cases where nested structures might lead to runtime errors:

Lastly, let’s look at a complex but common use case with destructuring and the spread operator to update state in a JavaScript object:

These examples reveal how assignment operators can be combined with other JavaScript features to produce sophisticated and efficient data manipulation. They exemplify the power packed into these seemingly simple operators and how, with creativity and understanding, they can be wielded to solve complex programming challenges. Whether you’re manipulating strings, toggling booleans with bitwise operations, handling default values, or safely updating nested objects, assignment operators simplify your workflow and clarify your intent to others reading your code.

Where to Go Next with Your Coding Journey

Embarking on the journey of coding can open a world of possibilities. If you’ve found a passion for programming and want to expand your skills beyond assignment operators, Zenva Academy is here to guide you every step of the way.

Our Python Mini-Degree program offers a deep dive into the versatile world of Python, covering a wide range of topics from basic programming concepts to more advanced applications. Python’s syntax is clear and intuitive, making it an excellent language for both beginners and seasoned developers. With it being in high demand across various fields, particularly data science, this Mini-Degree is the perfect opportunity to bolster your career prospects.

For those who wish to explore programming more broadly, we invite you to check out our comprehensive Programming courses . With over 250 courses to choose from, you’ll find content that takes you from beginner fundamentals to more complex topics, all designed to get you industry-ready. Join our community of over a million learners and developers and start transforming your future today!

In the digital tapestry of code, assignment operators are the threads that connect values to variables, creating the intricate patterns that bring applications to life. With the knowledge of these powerful tools, you’re now better equipped to write code that not only functions well but is efficient and easy to understand. As you continue to build and refine your programming skills, remember that each new concept you master is a stepping stone to more advanced and exciting challenges.

At Zenva, we’re passionate about empowering you to reach your full potential. Our Python Mini-Degree and extensive programming courses are designed specifically for learners like you, who are eager to grow their coding abilities and make their mark in the tech world. Join us, and let’s code the future together!

Did you come across any errors in this tutorial? Please let us know by completing this form and we’ll look into it!

Python Blog Image - What Are Assignment Operators - Complete Guide

FINAL DAYS: Unlock coding courses in Unity, Godot, Unreal, Python and more.

Continue Learning

ios game development

File Download Link

 alt=

Send me a download link for the files of .

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

' src=

Last Updated on June 23, 2023 by Prepbytes

why is assignment operator important

This type of operator is employed for transforming and assigning values to variables within an operation. In an assignment operation, the right side represents a value, while the left side corresponds to a variable. It is essential that the value on the right side has the same data type as the variable on the left side. If this requirement is not fulfilled, the compiler will issue an error.

What is Assignment Operator in C language?

In C, the assignment operator serves the purpose of assigning a value to a variable. It is denoted by the equals sign (=) and plays a vital role in storing data within variables for further utilization in code. When using the assignment operator, the value present on the right-hand side is assigned to the variable on the left-hand side. This fundamental operation allows developers to store and manipulate data effectively throughout their programs.

Example of Assignment Operator in C

For example, consider the following line of code:

Types of Assignment Operators in C

Here is a list of the assignment operators that you can find in the C language:

Simple assignment operator (=): This is the basic assignment operator, which assigns the value on the right-hand side to the variable on the left-hand side.

Addition assignment operator (+=): This operator adds the value on the right-hand side to the variable on the left-hand side and assigns the result back to the variable.

x += 3; // Equivalent to x = x + 3; (adds 3 to the current value of "x" and assigns the result back to "x")

Subtraction assignment operator (-=): This operator subtracts the value on the right-hand side from the variable on the left-hand side and assigns the result back to the variable.

x -= 4; // Equivalent to x = x – 4; (subtracts 4 from the current value of "x" and assigns the result back to "x")

* Multiplication assignment operator ( =):** This operator multiplies the value on the right-hand side with the variable on the left-hand side and assigns the result back to the variable.

x = 2; // Equivalent to x = x 2; (multiplies the current value of "x" by 2 and assigns the result back to "x")

Division assignment operator (/=): This operator divides the variable on the left-hand side by the value on the right-hand side and assigns the result back to the variable.

x /= 2; // Equivalent to x = x / 2; (divides the current value of "x" by 2 and assigns the result back to "x")

Bitwise AND assignment (&=): The bitwise AND assignment operator "&=" performs a bitwise AND operation between the value on the left-hand side and the value on the right-hand side. It then assigns the result back to the left-hand side variable.

x &= 3; // Binary: 0011 // After bitwise AND assignment: x = 1 (Binary: 0001)

Bitwise OR assignment (|=): The bitwise OR assignment operator "|=" performs a bitwise OR operation between the value on the left-hand side and the value on the right-hand side. It then assigns the result back to the left-hand side variable.

x |= 3; // Binary: 0011 // After bitwise OR assignment: x = 7 (Binary: 0111)

Bitwise XOR assignment (^=): The bitwise XOR assignment operator "^=" performs a bitwise XOR operation between the value on the left-hand side and the value on the right-hand side. It then assigns the result back to the left-hand side variable.

x ^= 3; // Binary: 0011 // After bitwise XOR assignment: x = 6 (Binary: 0110)

Left shift assignment (<<=): The left shift assignment operator "<<=" shifts the bits of the value on the left-hand side to the left by the number of positions specified by the value on the right-hand side. It then assigns the result back to the left-hand side variable.

x <<= 2; // Binary: 010100 (Shifted left by 2 positions) // After left shift assignment: x = 20 (Binary: 10100)

Right shift assignment (>>=): The right shift assignment operator ">>=" shifts the bits of the value on the left-hand side to the right by the number of positions specified by the value on the right-hand side. It then assigns the result back to the left-hand side variable.

x >>= 2; // Binary: 101 (Shifted right by 2 positions) // After right shift assignment: x = 5 (Binary: 101)

Conclusion The assignment operator in C, denoted by the equals sign (=), is used to assign a value to a variable. It is a fundamental operation that allows programmers to store data in variables for further use in their code. In addition to the simple assignment operator, C provides compound assignment operators that combine arithmetic or bitwise operations with assignment, allowing for concise and efficient code.

FAQs related to Assignment Operator in C

Q1. Can I assign a value of one data type to a variable of another data type? In most cases, assigning a value of one data type to a variable of another data type will result in a warning or error from the compiler. It is generally recommended to assign values of compatible data types to variables.

Q2. What is the difference between the assignment operator (=) and the comparison operator (==)? The assignment operator (=) is used to assign a value to a variable, while the comparison operator (==) is used to check if two values are equal. It is important not to confuse these two operators.

Q3. Can I use multiple assignment operators in a single statement? No, it is not possible to use multiple assignment operators in a single statement. Each assignment operator should be used separately for assigning values to different variables.

Q4. Are there any limitations on the right-hand side value of the assignment operator? The right-hand side value of the assignment operator should be compatible with the data type of the left-hand side variable. If the data types are not compatible, it may lead to unexpected behavior or compiler errors.

Q5. Can I assign the result of an expression to a variable using the assignment operator? Yes, it is possible to assign the result of an expression to a variable using the assignment operator. For example, x = y + z; assigns the sum of y and z to the variable x.

Q6. What happens if I assign a value to an uninitialized variable? Assigning a value to an uninitialized variable will initialize it with the assigned value. However, it is considered good practice to explicitly initialize variables before using them to avoid potential bugs or unintended behavior.

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

Null character in c, ackermann function in c, median of two sorted arrays of different size in c, number is palindrome or not in c, implementation of queue using linked list in c, c program to replace a substring in a string.

21.12 — Overloading the assignment operator

21.12 — Overloading the assignment operator

Table of Contents

Assignment operator, addition assignment operator, subtraction assignment operator, multiplication assignment operator, division assignment operator, modulus assignment operator, floor division assignment operator, exponentiation assignment operator, bitwise and assignment operator, bitwise or assignment operator, bitwise xor assignment operator , bitwise right shift assignment operator, bitwise left shift assignment operator, walrus operator, conclusion , python assignment operator: tips and tricks to learn.

Assignment Operators in Python

Assignment operators are vital in computer programming because they assign values to variables. Python stores and manipulates data with assignment operators like many other programming languages . First, let's review the fundamentals of Python assignment operators so you can understand the concept.

In Python, the following operators are often used for assignments:

Sign Type of Python Operators = Assignment Operator += Addition assignment -= Subtraction assignment *= Multiplication assignment /= Division assignment %= Modulus assignment //= Floor division assignment **= Exponentiation assignment &= Bitwise AND assignment |= Bitwise OR assignment ^= Bitwise XOR assignment >>= Bitwise right shift assignment <<= Bitwise left shift assignment := Walrus Operator

Python uses in-fix assignment operators to perform operations on variables or operands and assign values to the operand on the left side of the operator. It carries out calculations involving arithmetic, logical, and bitwise operations.

Python assignment operator provides a way to define assignment statements. This statement allows you to create, initialize, and update variables throughout your code, just like a software engineer . Variables are crucial in any code; assignment statements provide complete control over creating and modifying variables.

Understanding the Python assignment operator and how it is used in assignment statements can equip you with valuable tools to enhance the quality and reliability of your Python code.

In Python, the equals sign (=) is the primary assignment operator. It assigns the variable's value on the left side to the value on the right side of the operator.

Here's a sample to think about:

In this code snippet, the variable 'x' is given the value of 6. The assignment operator doesn't check for equality but assigns the value.

Become a Online Certifications Professional

  • 13 % CAGR Estimated Growth By 2026
  • 30 % Increase In Job Demand

Python Training

  • 24x7 learner assistance and support

Automation Testing Masters Program

  • Comprehensive blended learning program
  • 200 hours of Applied Learning

Here's what learners are saying regarding our programs:

Charlotte Martinez

Charlotte Martinez

This is a good course for beginners as well as experts with all the basic concepts explained clearly. It's a good starter to move to python programming for programmers as well as non- programmers

Daniel Altufaili

Daniel Altufaili

It infrastructure oprations , johnson electric.

Upon finishing the QA automation course, I received fresh assignments at my job owing to my heightened proficiency in IT, IoT, and ML. In addition to this, I earned a promotion and 20% salary increase. This course significantly expanded my expertise and motivated me to continuously enhance my skills through ongoing upskilling efforts.

The addition assignment operator (+=) adds the right-hand value to the left-hand variable.

The addition assignment operator syntax is variable += value.

The addition assignment operator increments a by 5. The console displays 14 as the result.

Also Read: Top Practical Applications of Python

The subtraction assignment operator subtracts a value from a variable and stores it in the same variable.

The subtraction assignment operator syntax is variable-=-value.

Using the multiplication assignment operator (=), multiply the value on the right by the variable's existing value on the left.

The assignment operator for multiplication has the following syntax: variable *= value

In this situation, the multiplication assignment operator multiplies the value of a by 2. The output, 10, is shown on the console.

Related Read: 16 Most Important Python Features and How to Use them

Using the division assignment operator (/=), divide the value of the left-hand variable by the value of the right-hand variable.

The assignment operator for division has the following syntax: variable /= value

Using the division assignment operator, divide a value by 3. The console displays 5.0.

Recommended Read: Why Choose Python? Discover Its Core Advantages!

The modulus assignment operator (% =) divides the left and right variable values by the modulus. The variable receives the remainder.

The modulus assignment operator syntax is variable %= value.

The modulus assignment operator divides a by 2. The console displays the following: 1.

Use "//" to divide and assign floors in one phrase. What "a//=b" means is "a=a//b". This operator cannot handle complicated numbers.

The floor division assignment operator syntax is variable == value.

The floor division assignment operator divides a by 2. The console displays 5.

The exponentiation assignment operator (=) elevates the left variable value to the right value's power.

Operator syntax for exponentiation assignment:

variable**=value

The exponentiation assignment operator raises a to 2. The console shows 9.

The bitwise AND assignment operator (&=) combines the left and right variable values using a bitwise AND operation. Results are assigned to variables.

The bitwise AND assignment operator syntax is variable &= value.

The bitwise AND assignment operator ANDes a with 2. The console displays 2 as the outcome.

The bitwise OR assignment operator (|=) bitwise ORs the left and right variable values.

The bitwise OR assignment operator syntax is variable == value.

A is ORed with 4 using the bitwise OR assignment operator. The console displays 6.

Use the bitwise XOR assignment operator (^=) to XOR the left and right values of a variable. Results are assigned to variables.

For bitwise XOR assignment, use the syntax: variable ^= value.

The bitwise XOR assignment operator XORs a with 4. The console displays 2 as the outcome.

The right shift assignment operator (>>=) shifts the variable's left value right by the number of places specified on the right.

The assignment operator for the bitwise right shift has the following syntax:

variable >>= value

The bitwise right shift assignment operator shifts 2 places to the right. The result is 1.

The variable value on the left moves left by the specified number of places on the right using the left shift assignment operator (<<=).

The bitwise left shift assignment operator syntax is variable <<= value.

When we execute a Bitwise right shift on 'a', we get 00011110, which is 30 in decimal.

Python gets new features with each update. Emily Morehouse added the walrus operator to Python 3.8's initial alpha. The most significant change in Python 3.8 is assignment expressions. The ":=" operator allows mid-expression variable assignment. This operator is called the walrus operator.

variable := expression

It was named for the operator symbol (:=), which resembled a sideways walrus' eyes and tusks.

Walrus operators simplify code authoring, which is its main benefit. Each user input was stored in a variable before being passed to the for loop to check its value or apply a condition. It is important to note that the walrus operator cannot be used alone.

With the walrus operator, you can simultaneously define a variable and return a value.

Above, we created two variables, myVar and value, with the phrase myVar = (value = 2346). The expression (value = 2346) defines the variable value using the walrus operator. It returns the value outside the parenthesis as if value = 2346 were a function. 

The variable myVar is initialized using the return value from the expression (value = 2346). 

The output shows that both variables have the same value.

Learn more about other Python operators by reading our detailed guide here .

Discover how Python assignment operators simplify and optimize programs. Python assignment operators are explained in length in this guide, along with examples, to help you understand them. Start this intriguing journey to improve your Python knowledge and programming skills with Simplilearn's Python training course .

1. What is the ":=" operator in Python?

Python's walrus operator ":" evaluates, assigns, and returns a value from a single sentence. Python 3.8 introduces it with this syntax (variable:=expression).

2. What does = mean in Python?

The most significant change in Python 3.8 is assignment expressions. The walrus operator allows mid-expression variable assignment.

3. What is def (:) Python?

The function definition in Python is (:). Functions are defined with def. A parameter or parameter(s) follows the function name. The function body begins with an indentation after the colon (:). The function body's return statement determines the value.

Our Software Development Courses Duration And Fees

Software Development Course typically range from a few weeks to several months, with fees varying based on program and institution.

Program NameDurationFees

Cohort Starts:

4 Months€ 2,499

Cohort Starts:

7 months€ 1,500

Cohort Starts:

6 Months€ 1,500

Cohort Starts:

8 months€ 1,099

Recommended Reads

Python Interview Guide

Filter in Python

Understanding Python If-Else Statement

Top Job Roles in the Field of Data Science

Yield in Python: An Ultimate Tutorial on Yield Keyword in Python

The Best Tips for Learning Python

Get Affiliated Certifications with Live Class programs

  • PMP, PMI, PMBOK, CAPM, PgMP, PfMP, ACP, PBA, RMP, SP, and OPM3 are registered marks of the Project Management Institute, Inc.

Stack Exchange Network

Stack Exchange network consists of 183 Q&A communities including Stack Overflow , the largest, most trusted online community for developers to learn, share their knowledge, and build their careers.

Q&A for work

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

Why does the assignment operator assign to the left-hand side?

I began teaching a friend programming just recently (we're using Python), and when we began discussing variable creation and the assignment operator, she asked why the value on the right is assigned to the name on the left, and not vice-versa.

I had not thought about it too much before, because it seemed natural to me, but she said that left-to-right seemed more natural to her, since that's how most of us read natural languages.

I thought about it, and concluded that it makes code much easier to read, since the names that are assigned to (which the programmer will need to reuse) are easily visible, aligned on the left.

As opposed to:

Now I wonder if there are other reasons as well for this standard. Is there a history behind it? Or is there some technical reason why this is a good option (I don't know much about compilers)? And are there any programming languages that assign to the right side?

  • language-design

voithos's user avatar

  • 15 R can assign to the right-hand side ( value -> variable ). –  You Commented Aug 3, 2011 at 22:06
  • 21 Is your friend's name... Yoda? –  Adriano Carneiro Commented Aug 4, 2011 at 16:36
  • 1 Reminds me of if (3 == i) to avoid the =/== typo –  BlackJack Commented Aug 4, 2011 at 20:28
  • 1 If she starts compaining about this, I wonder what will she do when she sees C++ & co. –  BlackBear Commented Aug 4, 2011 at 21:55
  • 3 Just a side note: Khan Academy has some lessons on Python for beginner programmers: khanacademy.org/#computer-science and Google has some for more advanced: code.google.com/edu/languages/google-python-class/set-up.html –  lindon fox Commented Aug 9, 2011 at 2:54

13 Answers 13

Ditto @paxdiablo. The early programming languages were written by mathematicians--actually all of them were. In mathematics, by her own principle--reading left to right-- it makes sense in the way it works.

x = 2y - 4.

In mathematics, you would say this: Let x be equal to 2y -4.

Also, even in algebra you do this. When you solve an equation for a variable, you isolate the variable you are solving for to the left side. i.e. y = mx + b;

Furthermore, once an entire family of languages-- such as the C family-- has a certain syntax, it is more costly to change.

surfasb's user avatar

  • 20 @FarmBoy: in mathematics, assignment and equality ARE the same thing, as there is no sequence in a formula as there is in computers. ( a equals b and at the same time b equals a ) –  Petruza Commented Aug 4, 2011 at 3:17
  • 1 @FB except in some single assignment functional languages like e.g. Erlang. Assignment and Assuring equality are the same like in mathematics –  Peer Stritzinger Commented Aug 4, 2011 at 6:00
  • 20 @Petruza No, in mathematics assignment and equality are not the same thing. If I say 'Let x = 2y - 3' it is different from 'Thus x = 2y - 3'. I math, typically context differentiates them. Since The comment disputing me was so universally acclaimed, I'll mention that I do have a Ph.D. in mathematics, I'm pretty sure about this. –  Eric Wilson Commented Aug 4, 2011 at 12:32
  • 2 I don't know mathematics anywhere near a PhD, what I state is that as there is no sequentiality, there's no order of execution in mathematics both in an assignment or in an equality, unlike programming, in which both sides of an assignment can be different at some point in time, and they end up being equal at some other point in time. But in mathematics, in an assignment like let a be... as there is no time, both sides of the assignment are equal as well, so the assignment is in fact an equality, no wonder why both use the same sign: = –  Petruza Commented Aug 4, 2011 at 18:47
  • 5 @Petruzza - but there is sequentiality. Mathematical documents are written from start to end, the same as any other document. If I assert x = 1 in chapter one, but assert x = 2 in chapter two, that isn't some terrible contradiction - each assertion applies only within a certain context. The difference in imperative programming is partly the removal of a barrier (we don't need a change of context), and partly about implementation and usefulness. –  user8709 Commented Aug 5, 2011 at 8:27

BASIC , one of the earliest computer languages had the "proper" form of:

which matches the mathematical mindset of specifying a variable, like "Let H be the height of the object".

COBOL was also similar with its COMPUTE statement. As with many ways of doing things, it may have simply been an arbitrary decision that was carried forward through many languages.

  • 7 I suppose that this form is more natural when program lines are considered as "statements" as opposed to "operations." As in, I declare that X must equal THIS , instead of the more linear Evaluate THIS and store it in X –  voithos Commented Aug 3, 2011 at 22:26
  • Wait, BASIC was an 'early' computer language? –  Alex Feinman Commented Aug 4, 2011 at 18:12
  • 2 @Alex Considering that it harkens from the 1960s, I'd say that's pretty early. –  Ben Richards Commented Aug 4, 2011 at 21:32
  • 1 On the other hand, in COBOL you could write MULTIPLY HEIGHT BY WIDTH GIVING AREA , so the variable that gets the result is on the very right side of the statement. –  user281377 Commented Aug 5, 2011 at 9:14

Actually, there is a programming language that assigns to the right side: TI-BASIC ! Not just that, but it also doesn't use '=' as the assignment operator, but rather uses an arrow known as the "STO" operator.

In the above example, three variables are being declared and given values. A would be 5, B would be 8, and C would be -3. The first declaration/assignment can be read 'store 5 as A'.

As to why TI-BASIC uses such a system for assignment, I attribute it to being because it is a programming language for a calculator. The "STO" operator on TI calculators was most often used in normal calculator operations after a number was calculated. If it was a number the user wanted to remember, they would hit the "STO" button, and the caclulator would prompt them for a name (automatically engaging the alpha lock so that keystrokes produced letters instead of numbers):

and the user could name the variable whatever they chose. Having to turn on alpha lock, type the name, then press "STO", and hitting the "Ans" key would have been far too cumbersome for normal operations. Since all calculator functions are available in TI-BASIC, no other assignment operators were added as "STO" performed the same task, albeit backwards when compared to most other languages.

(Anecdote: TI-BASIC was one of the first languages I learned, so when I when I was first learning Java in college I felt as though assigning to the LEFT was unusual and 'backwards'!)

diceguyd30's user avatar

  • +1 I totally forgot that ! TI Basic was my very first language, too, but I don't remember this detail. –  barjak Commented Aug 4, 2011 at 7:51
  • 1 Actually the STO operator is closer to how the machine works, and how any language actually operates. The value is first calculated and then stored in memory. –  Kratz Commented Aug 4, 2011 at 12:44

Heuristic 1: When faced with more than one possible way of doing something while designing a language, pick the most common, most intuitive one, or else you will end up with Perl+.

Now, how is it more natural (at least to an English speaker)? Let's look at how we write/say things in English:

Steven is now 10 years old (as opposed to 10 years old Steven now is). I weigh more than 190 pounds (as opposed to more than 190 pounds I weigh).

The following also sounds more natural:

"If Mary is 18 yo, then she can have a candy". "If I am younger than 21 yo, then I will ask my brother to by me tequila".

"If 18 yo Mary is ..." "If 21 is greater than my age ... "

Now the code:

Note that this is not natural to either programmers nor English speakers. The sentences sound like yoda-speak, and the code is nicknamed yoda-conditions. These might be helpful in C++, but I am sure most people would agree: if a compiler could do the heavy lifting and alleviate the need for yoda-conditions, life would be a bit easier.

Of course, one could get used to anything. For examples, number 81 is written as:

Eighty One (English) Eighty and one (Spanish) One and Eighty (German).

Finally, there are 4! = 24 valid ways of saying "green apple lies on table" in Russian - the order (almost) does not matter, except that 'on' must come together with 'table'. So, if you are a native Russian speaker (for example), then you might not care whether one writes a = 10 or 10 = a because both seem equally natural.

While linguistics is a fascinating subject, I never formally studied it and do not know that many languages. Hopefully I have provided enough counter-examples though.

Elias Mårtenson's user avatar

  • 4 ... and in French, 81 is said as "four times twenty one" ... :) –  Martin Sojka Commented Aug 4, 2011 at 7:25
  • 8 @Martin That's really weird, because four times twenty one is 84. –  Peter Olson Commented Aug 4, 2011 at 15:17
  • 7 @Peter: you've got your parenthesis wrong, it's (four times twenty) one –  SingleNegationElimination Commented Aug 4, 2011 at 20:36
  • 2 In French it's actually four twenty and one , then four twenty two (sans and ) up to four twenty ten nine (99). –  Jon Purdy Commented Aug 5, 2011 at 6:07
  • 4 @Job: Reading your "If 18 yo Mary is ...", I was inevitably reminded of Yoda saying "When nine hundred years old you reach, look as good you will not, hmm?" in Return of the Jedi :-) –  joriki Commented Aug 6, 2011 at 17:32

It started with FORTRAN in the 1950s. Where FORTRAN was an abbreviation of FORmula TRANslation -- the formulas in question being simple algebraic equations which by convention always assign to the left.

Its near contemporary COBOL on the other hand was meant to be English-like and assigned to the right (mostly!).

James Anderson's user avatar

  • I think this is the best example here because it perfectly illustrates a context in a language where it's readable to a common English speaker but has right assignment. I'm saying that's important because of the large amount of people saying in English it would only read left to right for the assignment to make sense, which is absolutely not true. –  Joshua Hedges Commented Aug 16, 2018 at 18:48

Well, as @diceguyd30 pointed out, there's both notations.

  • <Identifier> = <Value> means "let Identifier be Value ". Or to expand that: Define (or redefine) the variable Identifier to Value .
  • <Value> -> <Identifier> means "store Value to Identifier ". Or to expand that: Put Value into the location designated by Identifier .

Of course, generally speaking the Identifier may in fact be any L-value.

The first approach honors the abstract concept of variables, the second approach is more about actual storage.

Note that the first approach is also common in languages, that do not have assignments. Also note, that variable definition and assignment are relatively close <Type> <Identifier> = <Value> vs. <Identifier> = <Value> .

back2dos's user avatar

It could be a remnant of early parsing algorithms. Remember that LR parsing was only invented in 1965, and it could well be that LL parsers had troubles (within the time and space limitations of the machines at the time) going the other way around. Consider:

The two are clearly disambiguated from the second token. On the other hand,

Not fun. This gets worse when you start nesting assignment expressions.

Of course, easier to disambiguate for machines also means easier to disambiguate for humans. Another easy example would be searching for the initialization of any given identifier.

Easy, just look up the left side. Right side, on the other hand

Especially when you can't grep punch cards, it's much harder to find the identifier you want.

DeadMG's user avatar

  • Precisely the point that I had thought of, yes. –  voithos Commented Aug 8, 2011 at 0:31

As has already been mentioned, pretty well all the early computer languages worked that way. E.g. FORTRAN, which came along many years before BASIC.

It actually makes a great deal of sense to have the assigned variable on the left of the assignment expression. In some languages, you might have several different overloaded routines with the SAME NAME, returning different types of result. By letting the compiler see the type of the assigned variable first, it knows which overloaded routine to call, or what implicit cast to generate when converting from (e.g.) an integer to a float. That's a bit of a simplistic explanation, but hopefully you get the idea.

Dave Jewell's user avatar

  • 2 I understand your explanation, but could not the compiler just look ahead until the end of the statement? –  voithos Commented Aug 3, 2011 at 22:57
  • That might make the lexer simpler in today's languages, but how many programming languages even supported named methods, let alone method overloads, when this kind of syntax was new? –  user Commented Aug 4, 2011 at 9:27
  • 2 Hi @voithos. Yes - the compiler could look ahead, but that would probably have been an unacceptable level of complexity in the early days of compiler writing - which was often hand-coded assembler! I think that putting the assigned variable on the left is a pragmatic choice: it's easier for both man and machine to parse. –  Dave Jewell Commented Aug 4, 2011 at 9:55
  • I think it would be trivial for an assignment to assign to the right. When a expression like 3+4==6+7, both sides are evaluated before the operator is, because the language is defined recursively. The language element 'variable = expression', could easily be changed to 'expression = variable'. Whether or not that causes ambiguous situations depends on the rest of the language. –  Kratz Commented Aug 4, 2011 at 12:51
  • 1 @Kratz - that's certainly true for compilers now, but there may have been a minor issue for very old interpreted languages that worked with tokenized source. OTOH, that might have favored variable-on-the-right rather than variable-on-the-left. –  user8709 Commented Aug 5, 2011 at 9:59

Asssembly languages have the destination as part of the left-hand opcode. Higher level languages tended to follow the conventions of the predecessor languages.

When you see = (or := for Pascalish dialects), you could pronounce those as is assigned the value , then the left-to-right nature will make sense (because we also read left-to-right in most languages). Since programming languages were predominantly developed by folks who read left-to-right, the conventions stuck.

It is a type of path dependence . I suppose if computer programming was invented by people who spoke Hebrew or Arabic (or some other right-to-left language), then I suspect we'd be putting the destination on the right.

Tangurena's user avatar

  • Yes, but I suspect that the text in the editors would be right-aligned as well... –  voithos Commented Aug 3, 2011 at 22:55
  • 8 You can't generalise like that about assembly languages. They vary as to where the destination operand is. –  quickly_now Commented Aug 3, 2011 at 23:09
  • 2 @quickly_now: right; in fact, most of the primitive machine languages (not even assemblers by today's standards) didn't even have destination, as there was usually just one or two general-purpose accumulators. most operations implied the accumulator as destination, except for 'store' opcodes, which specified only the memory address and not the source (which was the accumulator). I really don't think it was any influence on assignment syntax for ALGOL-like languages. –  Javier Commented Aug 4, 2011 at 4:34
  • 3 @Tangurena - Some assembler languages have the destimation on the left. Not of the opcode (that's the assembled object code), but the left of the arguments list for the instruction mnemonic. However, others have the destination on the right. In 68000 assembler, you'd write mov.b #255, d0 , for instance, where d0 is the register to assign to. Older assemblers only have a single argument per instruction. In the 6502 LDA #255 (Load Accumulator), you could argue that the A is on the left, but it's also on the left in STA wherever (Store Accumulator). –  user8709 Commented Aug 5, 2011 at 9:05
  • 2 And even the Intel 4004 (the 4-bit ultimate ancestor of the 8086 family, with the 8008 and 8080 in between) was developed after assignment in high level languages. If you're assuming that the 8086 series is representative of what assemblers did in the 50s and earlier, I very much doubt that's true. –  user8709 Commented Aug 5, 2011 at 9:10

For what it's worth, most statements in COBOL read from left to right, so the two operands were named first, and the destination last, like: multiply salary by rate giving tax .

I won't however, suggest that your student might prefer COBOL, for fear that I'd be (quite rightly) flagged for making such a low, uncouth, tasteless comment! :-)

Jerry Coffin's user avatar

she said that left-to-right seemed more natural to her, since that's how most of us read natural languages.

I think this is a mistake. On the one hand, you can say "assign 10 to x" or "move 10 to x". On the other hand, you can say "set x to 10" or "x becomes 10".

In other words, depending on your choice of verb, the assigned-to variable may or may not be the subject, and may or may not be on the left. So "what is natural" just depends entirely on your habitual choice of wording to represent assignment.

In pseudocode the assignment operator is very commonly written on the right. For example

In Casio calculators, even non-programmable variants, the assignment variable is also displayed on the right

In Forth the variable is on the right, too

In x86, Intel syntax has the destination on the left, but GAS syntax reverses the order, making some confusion to many people, especially on instructions regarding parameters' order like subtraction or comparisons. These instructions are the same in 2 different dialects

They both move the value in rbx to rax. No other assembly languages I know write the destination on the right like GAS.

Some platforms put the expression on the left and the variable on the right: MOVE expression TO variable COBOL expression → variable TI-BASIC, Casio BASIC expression -> variable BETA, R put expression into variable LiveCode

https://en.wikipedia.org/wiki/Assignment_%28computer_science%29#Notation

Most languages assign the value to the left, one of the reasons being easy to align the operators, easier to read and recognize the variable, as the assignment operators and variables' positions will not vary wildly in the lines, and it's easier to read as "let variable be some value".

However some people prefer to say "move value x to y" and write the variable on the right.

phuclv's user avatar

I think it follows a logical way of thinking. There has to be a box (variable) first, then you put an object (value) inside it. You don't put the object in the air and then put a box around it.

Petruza's user avatar

  • 3 yes you do. in most languages the right side is evaluated before the left one. –  Javier Commented Aug 4, 2011 at 4:35
  • 3 Its a "Driving on the Right side of the road" type of thing. It seems logical but only because its the way you have always done it. All superior countries drive on the Left. –  James Anderson Commented Aug 4, 2011 at 8:33
  • 1 @JamesAnderson superior countries? :o –  nawfal Commented Jul 22, 2014 at 21:00
  • You're right, it's only logical for a left to right writing system as the roman alphabet, which I guess is used by almost every programming language, if not all. –  Petruza Commented Jul 24, 2014 at 0:35

Not the answer you're looking for? Browse other questions tagged language-design history or ask your own question .

  • The Overflow Blog
  • The hidden cost of speed
  • The creator of Jenkins discusses CI/CD and balancing business with open source
  • Featured on Meta
  • Announcing a change to the data-dump process
  • Bringing clarity to status tag usage on meta sites

Hot Network Questions

  • Issue with the roots of the Equation of Time
  • Largest number possible with +, -, ÷
  • When can the cat and mouse meet?
  • How is carousing different from drunkenness in Luke 21:34-36? How should they be interpreted literally and spiritually?
  • Is there a problem known to have no fastest algorithm, up to polynomials?
  • How to modify orphan row due to break at large footnote that spans two pages?
  • How rich is the richest person in a society satisfying the Pareto principle?
  • Can I replace the 'axiom schema of specification' in ZF by 'every subclass is a set'?
  • How should I tell my manager that he could delay my retirement with a raise?
  • What does "dare not" mean in a literary context?
  • Is it a good idea to perform I2C Communication in the ISR?
  • do-release-upgrade from 22.04 LTS to 24.04 LTS still no update available
  • Why is the soil in my yard moist?
  • Text wrapping in longtable not working
  • What's the radius of Mars over Mount Olympus?
  • What is the nature of the relationship between language and thought?
  • Pull up resistor question
  • Star Trek: The Next Generation episode that talks about life and death
  • Is a stable quantifier-free language really possible?
  • When has the SR-71 been used for civilian purposes?
  • An error in formula proposed by Riley et al to calculate the sample size
  • Why would op-amp shoot up to positive rail during power on?
  • Does a party have to wait 1d4 hours to start a Short Rest if no healing is available and an ally is only stabilized?
  • Environment for verbatim boxes

why is assignment operator important

  • C++ Data Types
  • C++ Input/Output
  • C++ Pointers
  • C++ Interview Questions
  • C++ Programs
  • C++ Cheatsheet
  • C++ Projects
  • C++ Exception Handling
  • C++ Memory Management

C++ Assignment Operator Overloading

Prerequisite: Operator Overloading

The assignment operator,”=”, is the operator used for Assignment. It copies the right value into the left value. Assignment Operators are predefined to operate only on built-in Data types.

  • Assignment operator overloading is binary operator overloading.
  • Overloading assignment operator in C++ copies all values of one object to another object.
  • Only a non-static member function should be used to overload the assignment operator.

In C++, the compiler automatically provides a default assignment operator for classes. This operator performs a shallow copy of each member of the class from one object to another. This means that if we don’t explicitly overload the assignment operator, the compiler will still allow us to assign one object to another using the assignment operator ( = ), and it won’t generate an error.

So, when we should perform assignment operator overloading? when our class involves dynamic memory allocation (e.g., pointers) and we need to perform a deep copy to prevent issues like double deletion or data corruption.

here, a and b are of type integer, which is a built-in data type. Assignment Operator can be used directly on built-in data types.

c1 and c2 are variables of type “class C”.

The above example can be done by implementing methods or functions inside the class, but we choose operator overloading instead. The reason for this is, operator overloading gives the functionality to use the operator directly which makes code easy to understand, and even code size decreases because of it. Also, operator overloading does not affect the normal working of the operator but provides extra functionality to it.

Now, if the user wants to use the assignment operator “=” to assign the value of the class variable to another class variable then the user has to redefine the meaning of the assignment operator “=”.  Redefining the meaning of operators really does not change their original meaning, instead, they have been given additional meaning along with their existing ones.

Also, always check if the object is not being assigned to itself (e.g., if (this != &other)), as assigning an object to itself does not make sense and may cause runtime issues.

While managing dynamic resources, the above approach of assignment overloading have few flaws and there is more efficient approach that is recommended. See this article for more info – Copy-and-Swap Idiom in C++

Please Login to comment...

Similar reads.

  • cpp-operator
  • cpp-operator-overloading
  • Top 10 Fun ESL Games and Activities for Teaching Kids English Abroad in 2024
  • Top Free Voice Changers for Multiplayer Games and Chat in 2024
  • Best Monitors for MacBook Pro and MacBook Air in 2024
  • 10 Best Laptop Brands in 2024
  • 15 Most Important Aptitude Topics For Placements [2024]

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

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

Why can some operators only be overloaded as member functions, other as friend functions and the rest of them as both?

Why can some operators only be overloaded as member functions, other as non-member "free" functions and the rest of them as both?

What is the rationale behind those?

How to remember which operators can be overloaded as what (member, free, or both)?

  • operator-overloading
  • member-functions

Yakk - Adam Nevraumont's user avatar

  • 5 @BROY Your edit is incorrect, a non-member function isn't necessarily a friend . (And I also find that your edit has changed a lot to the original question.) –  gx_ Commented Dec 14, 2013 at 11:57

4 Answers 4

The question lists three classes of operators. Putting them together on a list helps, I think, with understanding why a few operators are restricted in where they can be overloaded:

Operators which have to be overloaded as members. These are fairly few:

  • The assignment operator=() . Allowing non-member assignments seems to open the door for operators hijacking assignments, e.g., by overloading for different versions of const qualifications. Given that assignment operators are rather fundamental that seems to be undesirable.
  • The function call operator()() . The function call and overloading rules are sufficiently complicated as is. It seems ill-advised to complicate the rules further by allowing non-member function call operators.
  • The subscript operator[]() . Using interesting index types it seems that could interfere with accesses to operators. Although there is little danger of hijacking overloads, there doesn't seem to be much gain but interesting potential to write highly non-obvious code.
  • The class member access operator->() . Off-hand I can't see any bad abuse of overloading this operator a non-member. On the other hand, I also can't see any. Also, the class member access operator has rather special rules and playing with potential overloads interfering with these seems an unnecessary complication.

Although it is conceivable to overload each of these members are a non-member (especially the subscript operator which is works on arrays/pointers and these can be on either side of the call) it seems surprising if, e.g., an assignment could be hijacked by a non-member overload which which is a better match than one of the member assignments. These operators are also rather asymmetric: you generally wouldn't want to support conversion on both sides of an expression involving these operators.

That said, e.g., for a lambda expression library it would be nice if it were possible to overload all of these operators and I don't think there is an inherent technical reason to preventing these operators from being overloadable.

Operators which have to be overloaded as non-member functions.

  • The user-defined literal operator"" name()

This operator is somewhat of an odd-ball and, arguably not really really an operator. In any case, there is no object to call this member on for which members could be defined: the left argument of user-defined literals are always built-in types.

Not mentioned in the question but there are also operator which can't be overloaded at all:

  • The member selector .
  • The pointer-to-member object access operator .*
  • The scope operator ::
  • The ternary operator ?:

These four operators were considered to be too fundamental to be meddled with at all. Although there was a proposal to allow overloading operator.() at some point there isn't strong support doing so (the main use case would be smart references). Although there are certainly some contexts imaginable where it would be nice to overload these operators, too.

Operators which can be overloaded either as members or as non-members. This is the bulk of the operators:

  • The pre- and post-increment/-decrement operator++() , operator--() , operator++(int) , operator--(int)
  • The [unary] dereference operator*()
  • The [unary] address-of operator&()
  • The [unary] signs operator+() , operator-()
  • The logical negation operator!() (or operator not() )
  • The bitwise inversion operator~() (or operator compl() )
  • The comparisons operator==() , operator!=() , operator<() , operator>() , operator<=() , and operator>()
  • The [binary] arithmetic operator+() , operator-() , operator*() , operator/() , operator%()
  • The [binary] bitwise operator&() (or operator bitand() ), operator|() (or operator bit_or() ), operator^() (or operator xor() )
  • The bitwise shift operator<<() and operator>>()
  • The logic operator||() (or operator or() ) and operator&&() (or operator and() )
  • The operation/assignment operator@=() (for @ being a suitable operator symbol()
  • The sequence operator,() (for which overloading actually kills the sequence property!)
  • The pointer pointer-to-member access operator->*()
  • The memory management operator new() , operator new[]() , operator new[]() , and operator delete[]()
  • operator co_await() related to c++20 coroutines

The operators which can be overloaded either as members or as non-members are not as necessary for fundamental object maintenance as the other operators. That is not to say that they are not important. In fact, this list contains a few operators where it is rather questionable whether they should be overloadable (e. g., the address-of operator&() or the operators which normally cause sequencing, i. e., operator,() , operator||() , and operator&&() .

Of course, the C++ standard doesn't give a rationale on why things are done the way they are done (and there are also no records of the early days when these decisions where made). The best rationale can probably be found in "Design and Evolution of C++" by Bjarne Stroustrup. I recall that the operators were discussed there but there doesn't seem to be an electronic version available.

Overall, I don't think there are really strong reasons for the restrictions other than potential complication which was mostly not considered worth the effort. I would, however, doubt that the restrictions are likely to be lifted as the interactions with existing software are bound to change the meaning of some program in unpredictable ways.

Weijun Zhou's user avatar

The rationale is that it would not make sense for them to be non-members, as the thing on the left-hand side of the operator must be a class instance.

For example, assuming a class A

The last statement is really a call like this:

It would not make sense for the thing on the LHS of the . not to be an instance of A, and so the function must be a member.

Loki Astari's user avatar

  • 2 I can think of uses. For instance, class B might theoretically want to change how it is assigned to A by overloading operator=(A&,B), but B might for some reason not want to define a cast operator to A (for instance because you don't want the other implicit casts to occur). This desire might be unwise, against common practice, etc, but I'm not sure it's nonsensical or that you've (yet) made the case against it. –  Steve Jessop Commented Jul 15, 2009 at 17:53
  • Well, it doesn't really matter if I haven't made the case against - we have to accept what the standard says. And of course you can do (almost) anything you like via a named friend function. –  anon Commented Jul 15, 2009 at 18:00
  • 1 It makes sense to disallow such operations on primitive types, but why not allow a global operator[](const MyClass&, int) and make operator[](void ,int)* produce an error specifically because of the primitive type? –  Tim Sylvester Commented Jul 15, 2009 at 18:07
  • 4 "we have to accept what the standard says" - of course, but that does not exclude seeking a rationale. Usually, the committee made decisions for a reason. You've said the reason this is forbidden is that it "doesn't make sense". As opposed to, say, because some committee member slipped it into the standard while drunk ;-) –  Steve Jessop Commented Jul 15, 2009 at 18:56
  • 1 Why must it be a temporary? What's the difference between defining operator=(A&, const B&) as a free function, and defining swap(A&, B&) as a free function? I don't know, but if anyone does then it probably accounts for the reason that assignment operator has to be a member of A instead of free. –  Steve Jessop Commented Jul 16, 2009 at 1:38

Because you can't modify the semantics of primitive types. It wouldn't make sense to define how operator= works on an int , how to deference a pointer, or how an array access works.

Josh Kelley's user avatar

Here is one example: When you are overloading the << operator for a class T the signature will be:

where the implementation needs to be

For the << operator the first argument needs to be the ostream object and the second argument your class T object.

If you try to define operator<< as a member function you will not be allowed to define it as std::ostream operator<<(std::ostream& os, T& objT) . This is because binary operator member functions can only take one argument and the invoking object is implicitly passed in as the first argument using this .

If you use the std::ostream operator<<(std::ostream& os) signature as a member function you will actually end up with a member function std::ostream operator<<(this, std::ostream& os) which will not do what you want. Therefore you need a operator that is not a member function and can access member data (if your class T has private data you want to stream, operator<< needs to be a friend of class T).

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

  • The Overflow Blog
  • The hidden cost of speed
  • The creator of Jenkins discusses CI/CD and balancing business with open source
  • Featured on Meta
  • Announcing a change to the data-dump process
  • 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

  • Can I Use A Server In International Waters To Provide Illegal Content Without Getting Arrested?
  • Transform a list of rules into a list of function definitions
  • Largest number possible with +, -, ÷
  • What does "Two rolls" quote really mean?
  • A seven letter *
  • Pull up resistor question
  • Can I use Cat 6A to create a USB B 3.0 Superspeed?
  • Did the Turkish defense industry ever receive any significant foreign investment from any other OECD country?
  • What`s this? (Found among circulating tumor cells)
  • Environment for verbatim boxes
  • Star Trek: The Next Generation episode that talks about life and death
  • Gravitational potential energy of a water column
  • What would be a good weapon to use with size changing spell
  • Etymology of 制度
  • Why is notation in logic so different from algebra?
  • When can the cat and mouse meet?
  • Best approach to make lasagna fill pan
  • Nausea during high altitude cycling climbs
  • Sylvester primes
  • Why is the soil in my yard moist?
  • Are all citizens of Saudi Arabia "considered Muslims by the state"?
  • Pass vector of unquoted column names to a function and use first element
  • How was this character killed in Deadpool and Wolverine?
  • Why isn't a confidence level of anything >50% "good enough"?

why is assignment operator important

IMAGES

  1. With Assignment Operator

    why is assignment operator important

  2. Assignment operator

    why is assignment operator important

  3. PPT

    why is assignment operator important

  4. Assignment Operator || Assignment Statement || Compound assignment

    why is assignment operator important

  5. PPT

    why is assignment operator important

  6. Assignment Operator in Python

    why is assignment operator important

VIDEO

  1. Typescript Quiz Operator important topic Practice

  2. PGI Data Entry Operator Important Questions Class 2 #pgimer #dataentryoperator

  3. Why Assignment Class Is Very Important When You Book New House!

  4. WB POLICE DATA ENTRY OPERATOR||IMPORTANT TIPS REGARDING INTERVIEW AND TYPING TEST||WB POLICE JOB

  5. #20. Assignment Operators in Java

  6. Core

COMMENTS

  1. Assignment Operators in Programming

    Assignment operators are used in programming to assign values to variables. We use an assignment operator to store and update data within a program. They enable programmers to store data in variables and manipulate that data. The most common assignment operator is the equals sign (=), which assigns the value on the right side of the operator to ...

  2. Why should the assignment operator return a reference to the object?

    Always return a reference to the newly altered left hand side, return *this. This is to allow operator chaining, e.g. a = b = c;. Always check for self assignment (this == &rhs). This is especially important when your class does its own memory allocation. MyClass& MyClass::operator=(const MyClass &rhs) {.

  3. Why Assignment Operator Overloading Must Return Reference?

    When overloading the assignment operator in C++, it's important that it returns a reference to the object being assigned. There are several key reasons for this: 1. Chaining of Assignment Operations. In C++, assignment operations can be chained together. For example: A a, b, c; a = b = c; To support this chaining, the assignment operator must ...

  4. Python's Assignment Operator: Write Robust Assignments

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

  5. Assignment Operators in C

    1. "=": This is the simplest assignment operator. This operator is used to assign the value on the right to the variable on the left. Example: a = 10; b = 20; ch = 'y'; 2. "+=": This operator is combination of '+' and '=' operators.This operator first adds the current value of the variable on left to the value on the right and then assigns the result to the variable on the left.

  6. C Assignment Operators

    Code language:C++(cpp) The = assignment operator is called a simple assignment operator. It assigns the value of the left operand to the right operand. Besides the simple assignment operator, C supports compound assignment operators. A compound assignment operator performs the operation specified by the additional operator and then assigns the ...

  7. C Programming Assignment Operators

    Assignment Operators in C are used to assign values to the variables. They come under the category of binary operators as 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 "=".

  8. Assignment Operators In C With Proper Code Examples // Unstop

    For example, the expression x = 5 assigns the value of 5 to the variable x. Other assignment operators in C include addition assignment (+=), subtraction assignment (-=), multiplication assignment (*=), division assignment (/=), and modulus/ modulo assignment (%=). As their name suggests, they are used to assign the resultant value of addition ...

  9. Assignment operators

    Correct behavior. CWG 1527. C++11. for assignments to class type objects, the right operand could be an initializer list only when the assignment is defined by a user-defined assignment operator. removed user-defined assignment constraint. CWG 1538. C++11. E1 ={E2} was equivalent to E1 = T(E2) (T is the type of E1), this introduced a C-style cast.

  10. What Are Assignment Operators

    Basic Assignment Operator. The most common assignment operator is the simple equals sign (=), which assigns the value on its right to the variable on its left. Here's a straightforward example: let x = 5; console.log(x); // Outputs: 5. This operator is used to initialize variables, and it can also be used to reassign new values to existing variables:

  11. Assignment Operator in C

    The assignment operator (=) is used to assign a value to a variable, while the comparison operator (==) is used to check if two values are equal. It is important not to confuse these two operators. Q3. Can I use multiple assignment operators in a single statement? No, it is not possible to use multiple assignment operators in a single statement.

  12. Assignment Operators In C++

    In C++, the assignment operator can be combined into a single operator with some other operators to perform a combination of two operations in one single statement. These operators are called Compound Assignment Operators. ... Also, it is important to note that all of the above operators can be overloaded for custom operations with user-defined ...

  13. 21.12

    21.12 — Overloading the assignment operator. Alex July 22, 2024. The copy assignment operator (operator=) is used to copy values from one object to another already existing object. As of C++11, C++ also supports "Move assignment". We discuss move assignment in lesson 22.3 -- Move constructors and move assignment .

  14. Python Assignment Operator: A Comprehensive Guide 2024!

    Python uses in-fix assignment operators to perform operations on variables or operands and assign values to the operand on the left side of the operator. It carries out calculations involving arithmetic, logical, and bitwise operations. Python assignment operator provides a way to define assignment statements.

  15. Why do we need exactly the copy constructor and assignment operator in

    Because they are different things. Copy ctor will be called when you want to construct an new object from another one. Assignment operator will be called when you want to assign an existing object from another one, that means you might need to destroy/release some resources which the existing object hold before doing the assignment.

  16. When should we write our own assignment operator in C++?

    1) Do not allow assignment of one object to other object. We can create our own dummy assignment operator and make it private. 2) Write your own assignment operator that does deep copy. Same is true for Copy Constructor. Following is an example of overloading assignment operator for the above class. #include<iostream>.

  17. Why must the copy assignment operator return a reference/const

    Copy assignment should not return rvalue reference cos it may have the assigned object moved. Again take the assignment chain for example. a = b = c; // if a has a copy assignment overload that takes rvalue reference as argument like the following. X& operator=(X &&);

  18. Why does the assignment operator assign to the left-hand side?

    In pseudocode the assignment operator is very commonly written on the right. For example. 2*sqrt(x)/(3+y) -> z In Casio calculators, even non-programmable variants, the assignment variable is also displayed on the right. A+2B → C In Forth the variable is on the right, too. expression variable !

  19. C++ Assignment Operator Overloading

    C++ Assignment Operator Overloading

  20. c++

    To answer my rhetorical question: It means that a well-designed assignment operator should not need to check for self-assignment. Assigning an object to itself should work correctly (i.e. have the end-effect of "doing nothing") without performing an explicit check for self-assignment.

  21. c++

    The assignment operator=(). Allowing non-member assignments seems to open the door for operators hijacking assignments, e.g., by overloading for different versions of const qualifications. Given that assignment operators are rather fundamental that seems to be undesirable. The function call operator()(). The function call and overloading rules ...