- C++ Language
- Ascii Codes
- Boolean Operations
- Numerical Bases
![](http://nandemo.space/777/templates/cheerup1/res/banner1.gif)
Introduction
Basics of c++.
- Structure of a program
- Variables and types
- Basic Input/Output
Program structure
- Statements and flow control
- Overloads and templates
- Name visibility
Compound data types
- Character sequences
- Dynamic memory
- Data structures
- Other data types
- Classes (I)
- Classes (II)
- Special members
- Friendship and inheritance
- Polymorphism
Other language features
- Type conversions
- Preprocessor directives
Standard library
- Input/output with files
Assignment operator (=)
std; main () { a, b; a = 10; b = 4; a = b; b = 7; cout << ; cout << a; cout << ; cout << b; } |
Arithmetic operators ( +, -, *, /, % )
operator | description |
---|---|
addition | |
subtraction | |
multiplication | |
division | |
modulo |
Compound assignment (+=, -=, *=, /=, %=, >>=, <<=, &=, ^=, |=)
expression | equivalent to... |
---|---|
std; main () { a, b=3; a = b; a+=2; cout << a; } |
Increment and decrement (++, --)
Example 1 | Example 2 |
---|---|
Relational and comparison operators ( ==, !=, >, <, >=, <= )
operator | description |
---|---|
Equal to | |
Not equal to | |
Less than | |
Greater than | |
Less than or equal to | |
Greater than or equal to |
(5 > 4) (3 != 2) (6 >= 6) (5 < 5) |
(a*b >= c) (b+4 > a*c) ((b=2) == a) |
Logical operators ( !, &&, || )
!(6 <= 4) ! ! |
&& OPERATOR (and) | ||
---|---|---|
|| OPERATOR (or) | ||
---|---|---|
( (5 == 5) || (3 > 6) ) |
operator | short-circuit |
---|---|
if the left-hand side expression is , the combined result is (the right-hand side expression is never evaluated). | |
if the left-hand side expression is , the combined result is (the right-hand side expression is never evaluated). |
( (i<10) && (++i<n) ) { } |
Conditional ternary operator ( ? )
7==5+2 ? 4 : 3 5>3 ? a : b a>b ? a : b |
std; main () { a,b,c; a=2; b=7; c = (a>b) ? a : b; cout << c << ; } |
Comma operator ( , )
Bitwise operators ( &, |, ^, ~, <<, >> ).
operator | asm equivalent | description |
---|---|---|
Bitwise AND | ||
Bitwise inclusive OR | ||
Bitwise exclusive OR | ||
Unary complement (bit inversion) | ||
Shift bits left | ||
Shift bits right |
Explicit type casting operator
i; f = 3.14; i = ( ) f; |
(f); |
( ); |
Other operators
Precedence of operators.
x = (5 + 7) % 2; |
Level | Precedence group | Operator | Description | Grouping |
---|---|---|---|---|
1 | Scope | scope qualifier | Left-to-right | |
2 | Postfix (unary) | postfix increment / decrement | Left-to-right | |
functional forms | ||||
subscript | ||||
member access | ||||
3 | Prefix (unary) | prefix increment / decrement | Right-to-left | |
bitwise NOT / logical NOT | ||||
unary prefix | ||||
reference / dereference | ||||
allocation / deallocation | ||||
parameter pack | ||||
) | C-style type-casting | |||
4 | Pointer-to-member | access pointer | Left-to-right | |
5 | Arithmetic: scaling | multiply, divide, modulo | Left-to-right | |
6 | Arithmetic: addition | addition, subtraction | Left-to-right | |
7 | Bitwise shift | shift left, shift right | Left-to-right | |
8 | Relational | comparison operators | Left-to-right | |
9 | Equality | equality / inequality | Left-to-right | |
10 | And | bitwise AND | Left-to-right | |
11 | Exclusive or | bitwise XOR | Left-to-right | |
12 | Inclusive or | bitwise OR | Left-to-right | |
13 | Conjunction | logical AND | Left-to-right | |
14 | Disjunction | logical OR | Left-to-right | |
15 | Assignment-level expressions | assignment / compound assignment | Right-to-left | |
conditional operator | ||||
16 | Sequencing | comma separator | Left-to-right |
![assignment operator not equal Python's Assignment Operator: Write Robust Assignments](https://files.realpython.com/media/Pythons-Assignment-Statements-How-Do-They-Work_Watermarked.0a994e47f63c.jpg)
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 3.8 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.
![assignment operator not equal Python Tricks Dictionary Merge](https://realpython.com/static/pytrick-dict-merge.4201a0125a5e.png)
About Leodanis Pozo Ramos
![assignment operator not equal Leodanis Pozo Ramos](https://realpython.com/cdn-cgi/image/width=862,height=862,fit=crop,gravity=auto,format=auto/https://files.realpython.com/media/Perfil_final1.9f896bc212f6.jpg)
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:
![assignment operator not equal Aldren Santos](https://realpython.com/cdn-cgi/image/width=959,height=959,fit=crop,gravity=auto,format=auto/https://files.realpython.com/media/PP.9b8b026f75b8.jpg)
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.
This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
Assignment operators (C# reference)
- 11 contributors
The assignment operator = assigns the value of its right-hand operand to a variable, a property , or an indexer element given by its left-hand operand. The result of an assignment expression is the value assigned to the left-hand operand. The type of the right-hand operand must be the same as the type of the left-hand operand or implicitly convertible to it.
The assignment operator = is right-associative, that is, an expression of the form
is evaluated as
The following example demonstrates the usage of the assignment operator with a local variable, a property, and an indexer element as its left-hand operand:
The left-hand operand of an assignment receives the value of the right-hand operand. When the operands are of value types , assignment copies the contents of the right-hand operand. When the operands are of reference types , assignment copies the reference to the object.
This is called value assignment : the value is assigned.
ref assignment
Ref assignment = ref makes its left-hand operand an alias to the right-hand operand, as the following example demonstrates:
In the preceding example, the local reference variable arrayElement is initialized as an alias to the first array element. Then, it's ref reassigned to refer to the last array element. As it's an alias, when you update its value with an ordinary assignment operator = , the corresponding array element is also updated.
The left-hand operand of ref assignment can be a local reference variable , a ref field , and a ref , out , or in method parameter. Both operands must be of the same type.
Compound assignment
For a binary operator op , a compound assignment expression of the form
is equivalent to
except that x is only evaluated once.
Compound assignment is supported by arithmetic , Boolean logical , and bitwise logical and shift operators.
Null-coalescing assignment
You can use the null-coalescing assignment operator ??= to assign the value of its right-hand operand to its left-hand operand only if the left-hand operand evaluates to null . For more information, see the ?? and ??= operators article.
Operator overloadability
A user-defined type can't overload the assignment operator. However, a user-defined type can define an implicit conversion to another type. That way, the value of a user-defined type can be assigned to a variable, a property, or an indexer element of another type. For more information, see User-defined conversion operators .
A user-defined type can't explicitly overload a compound assignment operator. However, if a user-defined type overloads a binary operator op , the op= operator, if it exists, is also implicitly overloaded.
C# language specification
For more information, see the Assignment operators section of the C# language specification .
- C# operators and expressions
- ref keyword
- Use compound assignment (style rules IDE0054 and IDE0074)
Coming soon: Throughout 2024 we will be phasing out GitHub Issues as the feedback mechanism for content and replacing it with a new feedback system. For more information see: https://aka.ms/ContentUserFeedback .
Submit and view feedback for
Additional resources
What's the Difference Between the Assignment (`=`) and Equality (`==`, `===`) Operators?
![assignment operator not equal](https://sentry.io/static/ghost-a2dfd8493b850dc0d9a9b1b4a41011c6.png)
.css-13lojzj{position:absolute;padding-right:0.25rem;margin-left:-1.25rem;left:0;height:100%;display:-webkit-inline-box;display:-webkit-inline-flex;display:-ms-inline-flexbox;display:inline-flex;-webkit-align-items:center;-webkit-box-align:center;-ms-flex-align:center;align-items:center;display:none;} .css-b94zdx{width:1rem;height:1rem;} The Problem .css-1s1dm52{margin-left:1rem;}.css-1s1dm52.btn-small{font-size:0.8125rem;font-weight:500;height:auto;line-height:0.75rem;padding:0.5rem 0.75rem;} .css-vgbcnb{margin-left:1rem;}.css-vgbcnb.snackbar{height:auto;padding:0.5rem 0.75rem;}.css-vgbcnb.btn-small{font-size:0.8125rem;font-weight:500;height:auto;line-height:0.75rem;padding:0.5rem 0.75rem;} .css-16p7d4d{margin-left:1rem;}.css-16p7d4d.snackbar{height:auto;padding:0.5rem 0.75rem;}.css-16p7d4d.btn-small{font-size:0.8125rem;font-weight:500;height:auto;line-height:0.75rem;padding:0.5rem 0.75rem;} Jump To Solution
People who are new to programming often find it difficult to understand the difference between = , == , and === .
In mathematics we only use = , so what do the other two mean?
The Solution
The = is an assignment operator, while == and === are called equality operators.
Assignment Operator ( = )
In mathematics and algebra, = is an equal to operator. In programming = is an assignment operator , which means that it assigns a value to a variable.
For example, the following code will store a value of 5 in the variable x :
We can combine the declaration and assignment in one line:
It may look like the assignment operator works the same way as algebra’s equal to operator, but that’s not the case.
For example, the following doesn’t make any sense in algebra:
But it is acceptable in JavaScript (and other programming languages). JavaScript will take the expression on the right-hand side of the operator x + 4 and store this value in x again.
Equality Operator ( == )
In JavaScript, the operator that compares two values is written like this: == . It is called an equality operator . The equality operator is one of the many comparison operators in JavaScript that are used in logical and conditional statements.
The equality operator returns true or false based on whether the operands (the values being compared) are equal.
For example, the following code will return false :
Interestingly, if we compare an integer 5 and a string "5" it returns true .
That is because in most cases, if the two operands are not of the same type, JavaScript attempts to convert them to an appropriate type for comparison. This behavior generally results in comparing the operands numerically.
Strict Equality Operator ( === )
Like the equality operator above, the strict equality operator compares the two values. But unlike the equality operator, the strict equality operator compares both the content and the type of the operands.
So using the strict equality operator, 5 and "5" are not equal.
It is better to use the strict equality operator to prevent type conversions, which may result in unexpected bugs. But if you’re certain the types on both sides will be the same, there is no problem with using the shorter operator.
- Resources JavaScript Frontend Error Monitoring 101
![assignment operator not equal Syntax.fm logo](https://www.sentry.dev/static/d2983c9c677bc9bf755cb7e87f5328d2/d5e77/syntax-logo.png)
Tasty treats for web developers brought to you by Sentry. Get tips and tricks from Wes Bos and Scott Tolinski.
Loved by over 4 million developers and more than 100,000 organizations worldwide, Sentry provides code-level observability to many of the world’s best-known companies like Disney, Peloton, Cloudflare, Eventbrite, Slack, Supercell, and Rockstar Games. Each month we process billions of exceptions from the most popular products on the internet.
A peek at your privacy
Here’s a quick look at how Sentry handles your personal information (PII).
Who we collect PII from
We collect PII about people browsing our website, users of the Sentry service, prospective customers, and people who otherwise interact with us.
What if my PII is included in data sent to Sentry by a Sentry customer (e.g., someone using Sentry to monitor their app)? In this case you have to contact the Sentry customer (e.g., the maker of the app). We do not control the data that is sent to us through the Sentry service for the purposes of application monitoring.
PII we may collect about you
- PII provided by you and related to your
- Account, profile, and login
- Requests and inquiries
- PII collected from your device and usage
- PII collected from third parties (e.g., social media)
How we use your PII
- To operate our site and service
- To protect and improve our site and service
- To provide customer care and support
- To communicate with you
- For other purposes (that we inform you of at collection)
Third parties who receive your PII
We may disclose your PII to the following type of recipients:
- Subsidiaries and other affiliates
- Service providers
- Partners (go-to-market, analytics)
- Third-party platforms (when you connect them to our service)
- Governmental authorities (where necessary)
- An actual or potential buyer
We use cookies (but not for advertising)
- We do not use advertising or targeting cookies
- We use necessary cookies to run and improve our site and service
- You can disable cookies but this can impact your use or access to certain parts of our site and service
Know your rights
You may have the following rights related to your PII:
- Access, correct, and update
- Object to or restrict processing
- Opt-out of marketing
- Be forgotten by Sentry
- Withdraw your consent
- Complain about us
If you have any questions or concerns about your privacy at Sentry, please email us at [email protected] .
If you are a California resident, see our Supplemental notice .
- Skip to main content
- Select language
- Skip to search
- Expressions and operators
- Operator precedence
Left-hand-side expressions
« Previous Next »
This chapter describes JavaScript's expressions and operators, including assignment, comparison, arithmetic, bitwise, logical, string, ternary and more.
A complete and detailed list of operators and expressions is also available in the reference .
JavaScript has the following types of operators. This section describes the operators and contains information about operator precedence.
- Assignment operators
- Comparison operators
- Arithmetic operators
- Bitwise operators
Logical operators
String operators, conditional (ternary) operator.
- Comma operator
Unary operators
- Relational operator
JavaScript has both binary and unary operators, and one special ternary operator, the conditional operator. A binary operator requires two operands, one before the operator and one after the operator:
For example, 3+4 or x*y .
A unary operator requires a single operand, either before or after the operator:
For example, x++ or ++x .
An assignment operator assigns a value to its left operand based on the value of its right operand. The simple assignment operator is equal ( = ), which assigns the value of its right operand to its left operand. That is, x = y assigns the value of y to x .
There are also compound assignment operators that are shorthand for the operations listed in the following table:
Name | Shorthand operator | Meaning |
---|---|---|
Destructuring
For more complex assignments, the destructuring assignment syntax is a JavaScript expression that makes it possible to extract data from arrays or objects using a syntax that mirrors the construction of array and object literals.
A comparison operator compares its operands and returns a logical value based on whether the comparison is true. The operands can be numerical, string, logical, or object values. Strings are compared based on standard lexicographical ordering, using Unicode values. In most cases, if the two operands are not of the same type, JavaScript attempts to convert them to an appropriate type for the comparison. This behavior generally results in comparing the operands numerically. The sole exceptions to type conversion within comparisons involve the === and !== operators, which perform strict equality and inequality comparisons. These operators do not attempt to convert the operands to compatible types before checking equality. The following table describes the comparison operators in terms of this sample code:
Operator | Description | Examples returning true |
---|---|---|
( ) | Returns if the operands are equal. |
|
( ) | Returns if the operands are not equal. | |
( ) | Returns if the operands are equal and of the same type. See also and . | |
( ) | Returns if the operands are of the same type but not equal, or are of different type. | |
( ) | Returns if the left operand is greater than the right operand. | |
( ) | Returns if the left operand is greater than or equal to the right operand. | |
( ) | Returns if the left operand is less than the right operand. | |
( ) | Returns if the left operand is less than or equal to the right operand. |
Note: ( => ) is not an operator, but the notation for Arrow functions .
An arithmetic operator takes numerical values (either literals or variables) as their operands and returns a single numerical value. The standard arithmetic operators are addition ( + ), subtraction ( - ), multiplication ( * ), and division ( / ). These operators work as they do in most other programming languages when used with floating point numbers (in particular, note that division by zero produces Infinity ). For example:
In addition to the standard arithmetic operations (+, -, * /), JavaScript provides the arithmetic operators listed in the following table:
Operator | Description | Example |
---|---|---|
( ) | Binary operator. Returns the integer remainder of dividing the two operands. | 12 % 5 returns 2. |
( ) | Unary operator. Adds one to its operand. If used as a prefix operator ( ), returns the value of its operand after adding one; if used as a postfix operator ( ), returns the value of its operand before adding one. | If is 3, then sets to 4 and returns 4, whereas returns 3 and, only then, sets to 4. |
( ) | Unary operator. Subtracts one from its operand. The return value is analogous to that for the increment operator. | If is 3, then sets to 2 and returns 2, whereas returns 3 and, only then, sets to 2. |
( ) | Unary operator. Returns the negation of its operand. | If is 3, then returns -3. |
( ) | Unary operator. Attempts to convert the operand to a number, if it is not already. | returns . returns |
( ) | Calculates the to the power, that is, | returns . returns . |
A bitwise operator treats their operands as a set of 32 bits (zeros and ones), rather than as decimal, hexadecimal, or octal numbers. For example, the decimal number nine has a binary representation of 1001. Bitwise operators perform their operations on such binary representations, but they return standard JavaScript numerical values.
The following table summarizes JavaScript's bitwise operators.
Operator | Usage | Description |
---|---|---|
Returns a one in each bit position for which the corresponding bits of both operands are ones. | ||
Returns a zero in each bit position for which the corresponding bits of both operands are zeros. | ||
Returns a zero in each bit position for which the corresponding bits are the same. [Returns a one in each bit position for which the corresponding bits are different.] | ||
Inverts the bits of its operand. | ||
Shifts in binary representation bits to the left, shifting in zeros from the right. | ||
Shifts in binary representation bits to the right, discarding bits shifted off. | ||
Shifts in binary representation bits to the right, discarding bits shifted off, and shifting in zeros from the left. |
Bitwise logical operators
Conceptually, the bitwise logical operators work as follows:
- The operands are converted to thirty-two-bit integers and expressed by a series of bits (zeros and ones). Numbers with more than 32 bits get their most significant bits discarded. For example, the following integer with more than 32 bits will be converted to a 32 bit integer: Before: 11100110111110100000000000000110000000000001 After: 10100000000000000110000000000001
- Each bit in the first operand is paired with the corresponding bit in the second operand: first bit to first bit, second bit to second bit, and so on.
- The operator is applied to each pair of bits, and the result is constructed bitwise.
For example, the binary representation of nine is 1001, and the binary representation of fifteen is 1111. So, when the bitwise operators are applied to these values, the results are as follows:
Expression | Result | Binary Description |
---|---|---|
Note that all 32 bits are inverted using the Bitwise NOT operator, and that values with the most significant (left-most) bit set to 1 represent negative numbers (two's-complement representation).
Bitwise shift operators
The bitwise shift operators take two operands: the first is a quantity to be shifted, and the second specifies the number of bit positions by which the first operand is to be shifted. The direction of the shift operation is controlled by the operator used.
Shift operators convert their operands to thirty-two-bit integers and return a result of the same type as the left operand.
The shift operators are listed in the following table.
Operator | Description | Example |
---|---|---|
( ) | This operator shifts the first operand the specified number of bits to the left. Excess bits shifted off to the left are discarded. Zero bits are shifted in from the right. | yields 36, because 1001 shifted 2 bits to the left becomes 100100, which is 36. |
( ) | This operator shifts the first operand the specified number of bits to the right. Excess bits shifted off to the right are discarded. Copies of the leftmost bit are shifted in from the left. | yields 2, because 1001 shifted 2 bits to the right becomes 10, which is 2. Likewise, yields -3, because the sign is preserved. |
( ) | This operator shifts the first operand the specified number of bits to the right. Excess bits shifted off to the right are discarded. Zero bits are shifted in from the left. | yields 4, because 10011 shifted 2 bits to the right becomes 100, which is 4. For non-negative numbers, zero-fill right shift and sign-propagating right shift yield the same result. |
Logical operators are typically used with Boolean (logical) values; when they are, they return a Boolean value. However, the && and || operators actually return the value of one of the specified operands, so if these operators are used with non-Boolean values, they may return a non-Boolean value. The logical operators are described in the following table.
Operator | Usage | Description |
---|---|---|
( ) | Returns if it can be converted to ; otherwise, returns . Thus, when used with Boolean values, returns if both operands are true; otherwise, returns . | |
( ) | Returns if it can be converted to ; otherwise, returns . Thus, when used with Boolean values, returns if either operand is true; if both are false, returns . | |
( ) | Returns if its single operand can be converted to ; otherwise, returns . |
Examples of expressions that can be converted to false are those that evaluate to null, 0, NaN, the empty string (""), or undefined.
The following code shows examples of the && (logical AND) operator.
The following code shows examples of the || (logical OR) operator.
The following code shows examples of the ! (logical NOT) operator.
Short-circuit evaluation
As logical expressions are evaluated left to right, they are tested for possible "short-circuit" evaluation using the following rules:
- false && anything is short-circuit evaluated to false.
- true || anything is short-circuit evaluated to true.
The rules of logic guarantee that these evaluations are always correct. Note that the anything part of the above expressions is not evaluated, so any side effects of doing so do not take effect.
In addition to the comparison operators, which can be used on string values, the concatenation operator (+) concatenates two string values together, returning another string that is the union of the two operand strings.
For example,
The shorthand assignment operator += can also be used to concatenate strings.
The conditional operator is the only JavaScript operator that takes three operands. The operator can have one of two values based on a condition. The syntax is:
If condition is true, the operator has the value of val1 . Otherwise it has the value of val2 . You can use the conditional operator anywhere you would use a standard operator.
This statement assigns the value "adult" to the variable status if age is eighteen or more. Otherwise, it assigns the value "minor" to status .
The comma operator ( , ) simply evaluates both of its operands and returns the value of the last operand. This operator is primarily used inside a for loop, to allow multiple variables to be updated each time through the loop.
For example, if a is a 2-dimensional array with 10 elements on a side, the following code uses the comma operator to update two variables at once. The code prints the values of the diagonal elements in the array:
A unary operation is an operation with only one operand.
The delete operator deletes an object, an object's property, or an element at a specified index in an array. The syntax is:
where objectName is the name of an object, property is an existing property, and index is an integer representing the location of an element in an array.
The fourth form is legal only within a with statement, to delete a property from an object.
You can use the delete operator to delete variables declared implicitly but not those declared with the var statement.
If the delete operator succeeds, it sets the property or element to undefined . The delete operator returns true if the operation is possible; it returns false if the operation is not possible.
Deleting array elements
When you delete an array element, the array length is not affected. For example, if you delete a[3] , a[4] is still a[4] and a[3] is undefined.
When the delete operator removes an array element, that element is no longer in the array. In the following example, trees[3] is removed with delete . However, trees[3] is still addressable and returns undefined .
If you want an array element to exist but have an undefined value, use the undefined keyword instead of the delete operator. In the following example, trees[3] is assigned the value undefined , but the array element still exists:
The typeof operator is used in either of the following ways:
The typeof operator returns a string indicating the type of the unevaluated operand. operand is the string, variable, keyword, or object for which the type is to be returned. The parentheses are optional.
Suppose you define the following variables:
The typeof operator returns the following results for these variables:
For the keywords true and null , the typeof operator returns the following results:
For a number or string, the typeof operator returns the following results:
For property values, the typeof operator returns the type of value the property contains:
For methods and functions, the typeof operator returns results as follows:
For predefined objects, the typeof operator returns results as follows:
The void operator is used in either of the following ways:
The void operator specifies an expression to be evaluated without returning a value. expression is a JavaScript expression to evaluate. The parentheses surrounding the expression are optional, but it is good style to use them.
You can use the void operator to specify an expression as a hypertext link. The expression is evaluated but is not loaded in place of the current document.
The following code creates a hypertext link that does nothing when the user clicks it. When the user clicks the link, void(0) evaluates to undefined , which has no effect in JavaScript.
The following code creates a hypertext link that submits a form when the user clicks it.
![](http://nandemo.space/777/templates/cheerup1/res/banner1.gif)
Relational operators
A relational operator compares its operands and returns a Boolean value based on whether the comparison is true.
The in operator returns true if the specified property is in the specified object. The syntax is:
where propNameOrNumber is a string or numeric expression representing a property name or array index, and objectName is the name of an object.
The following examples show some uses of the in operator.
The instanceof operator returns true if the specified object is of the specified object type. The syntax is:
where objectName is the name of the object to compare to objectType , and objectType is an object type, such as Date or Array .
Use instanceof when you need to confirm the type of an object at runtime. For example, when catching exceptions, you can branch to different exception-handling code depending on the type of exception thrown.
For example, the following code uses instanceof to determine whether theDay is a Date object. Because theDay is a Date object, the statements in the if statement execute.
The precedence of operators determines the order they are applied when evaluating an expression. You can override operator precedence by using parentheses.
The following table describes the precedence of operators, from highest to lowest.
Operator type | Individual operators |
---|---|
member | |
call / create instance | |
negation/increment | |
multiply/divide | |
addition/subtraction | |
bitwise shift | |
relational | |
equality | |
bitwise-and | |
bitwise-xor | |
bitwise-or | |
logical-and | |
logical-or | |
conditional | |
assignment | |
comma |
A more detailed version of this table, complete with links to additional details about each operator, may be found in JavaScript Reference .
- Expressions
An expression is any valid unit of code that resolves to a value.
Every syntactically valid expression resolves to some value but conceptually, there are two types of expressions: with side effects (for example: those that assign value to a variable) and those that in some sense evaluates and therefore resolves to value.
The expression x = 7 is an example of the first type. This expression uses the = operator to assign the value seven to the variable x . The expression itself evaluates to seven.
The code 3 + 4 is an example of the second expression type. This expression uses the + operator to add three and four together without assigning the result, seven, to a variable. JavaScript has the following expression categories:
- Arithmetic: evaluates to a number, for example 3.14159. (Generally uses arithmetic operators .)
- String: evaluates to a character string, for example, "Fred" or "234". (Generally uses string operators .)
- Logical: evaluates to true or false. (Often involves logical operators .)
- Primary expressions: Basic keywords and general expressions in JavaScript.
- Left-hand-side expressions: Left values are the destination of an assignment.
Primary expressions
Basic keywords and general expressions in JavaScript.
Use the this keyword to refer to the current object. In general, this refers to the calling object in a method. Use this either with the dot or the bracket notation:
Suppose a function called validate validates an object's value property, given the object and the high and low values:
You could call validate in each form element's onChange event handler, using this to pass it the form element, as in the following example:
- Grouping operator
The grouping operator ( ) controls the precedence of evaluation in expressions. For example, you can override multiplication and division first, then addition and subtraction to evaluate addition first.
Comprehensions
Comprehensions are an experimental JavaScript feature, targeted to be included in a future ECMAScript version. There are two versions of comprehensions:
Comprehensions exist in many programming languages and allow you to quickly assemble a new array based on an existing one, for example.
Left values are the destination of an assignment.
You can use the new operator to create an instance of a user-defined object type or of one of the built-in object types. Use new as follows:
The super keyword is used to call functions on an object's parent. It is useful with classes to call the parent constructor, for example.
Spread operator
The spread operator allows an expression to be expanded in places where multiple arguments (for function calls) or multiple elements (for array literals) are expected.
Example: Today if you have an array and want to create a new array with the existing one being part of it, the array literal syntax is no longer sufficient and you have to fall back to imperative code, using a combination of push , splice , concat , etc. With spread syntax this becomes much more succinct:
Similarly, the spread operator works with function calls:
Document Tags and Contributors
- l10n:priority
- JavaScript basics
- JavaScript first steps
- JavaScript building blocks
- Introducing JavaScript objects
- Introduction
- Grammar and types
- Control flow and error handling
- Loops and iteration
- Numbers and dates
- Text formatting
- Regular expressions
- Indexed collections
- Keyed collections
- Working with objects
- Details of the object model
- Iterators and generators
- Meta programming
- A re-introduction to JavaScript
- JavaScript data structures
- Equality comparisons and sameness
- Inheritance and the prototype chain
- Strict mode
- JavaScript typed arrays
- Memory Management
- Concurrency model and Event Loop
- References:
- ArrayBuffer
- AsyncFunction
- Float32Array
- Float64Array
- GeneratorFunction
- InternalError
- Intl.Collator
- Intl.DateTimeFormat
- Intl.NumberFormat
- ParallelArray
- ReferenceError
- SIMD.Bool16x8
- SIMD.Bool32x4
- SIMD.Bool64x2
- SIMD.Bool8x16
- SIMD.Float32x4
- SIMD.Float64x2
- SIMD.Int16x8
- SIMD.Int32x4
- SIMD.Int8x16
- SIMD.Uint16x8
- SIMD.Uint32x4
- SIMD.Uint8x16
- SharedArrayBuffer
- StopIteration
- SyntaxError
- Uint16Array
- Uint32Array
- Uint8ClampedArray
- WebAssembly
- decodeURI()
- decodeURIComponent()
- encodeURI()
- encodeURIComponent()
- parseFloat()
- Array comprehensions
- Conditional (ternary) Operator
- Destructuring assignment
- Expression closures
- Generator comprehensions
- Legacy generator function expression
- Logical Operators
- Object initializer
- Property accessors
- Spread syntax
- async function expression
- class expression
- delete operator
- function expression
- function* expression
- in operator
- new operator
- void operator
- Legacy generator function
- async function
- for each...in
- function declaration
- try...catch
- Arguments object
- Arrow functions
- Default parameters
- Method definitions
- Rest parameters
- constructor
- element loaded from a different domain for which you violated the same-origin policy.">Error: Permission denied to access property "x"
- InternalError: too much recursion
- RangeError: argument is not a valid code point
- RangeError: invalid array length
- RangeError: invalid date
- RangeError: precision is out of range
- RangeError: radix must be an integer
- RangeError: repeat count must be less than infinity
- RangeError: repeat count must be non-negative
- ReferenceError: "x" is not defined
- ReferenceError: assignment to undeclared variable "x"
- ReferenceError: can't access lexical declaration`X' before initialization
- ReferenceError: deprecated caller or arguments usage
- ReferenceError: invalid assignment left-hand side
- ReferenceError: reference to undefined property "x"
- SyntaxError: "0"-prefixed octal literals and octal escape seq. are deprecated
- SyntaxError: "use strict" not allowed in function with non-simple parameters
- SyntaxError: "x" is a reserved identifier
- SyntaxError: JSON.parse: bad parsing
- SyntaxError: Malformed formal parameter
- SyntaxError: Unexpected token
- SyntaxError: Using //@ to indicate sourceURL pragmas is deprecated. Use //# instead
- SyntaxError: a declaration in the head of a for-of loop can't have an initializer
- SyntaxError: applying the 'delete' operator to an unqualified name is deprecated
- SyntaxError: for-in loop head declarations may not have initializers
- SyntaxError: function statement requires a name
- SyntaxError: identifier starts immediately after numeric literal
- SyntaxError: illegal character
- SyntaxError: invalid regular expression flag "x"
- SyntaxError: missing ) after argument list
- SyntaxError: missing ) after condition
- SyntaxError: missing : after property id
- SyntaxError: missing ; before statement
- SyntaxError: missing = in const declaration
- SyntaxError: missing ] after element list
- SyntaxError: missing formal parameter
- SyntaxError: missing name after . operator
- SyntaxError: missing variable name
- SyntaxError: missing } after function body
- SyntaxError: missing } after property list
- SyntaxError: redeclaration of formal parameter "x"
- SyntaxError: return not in function
- SyntaxError: test for equality (==) mistyped as assignment (=)?
- SyntaxError: unterminated string literal
- TypeError: "x" has no properties
- TypeError: "x" is (not) "y"
- TypeError: "x" is not a constructor
- TypeError: "x" is not a function
- TypeError: "x" is not a non-null object
- TypeError: "x" is read-only
- TypeError: More arguments needed
- TypeError: can't access dead object
- TypeError: can't define property "x": "obj" is not extensible
- TypeError: can't delete non-configurable array element
- TypeError: can't redefine non-configurable property "x"
- TypeError: cyclic object value
- TypeError: invalid 'in' operand "x"
- TypeError: invalid Array.prototype.sort argument
- TypeError: invalid arguments
- TypeError: invalid assignment to const "x"
- TypeError: property "x" is non-configurable and can't be deleted
- TypeError: setting getter-only property "x"
- TypeError: variable "x" redeclares argument
- URIError: malformed URI sequence
- Warning: -file- is being assigned a //# sourceMappingURL, but already has one
- Warning: 08/09 is not a legal ECMA-262 octal constant
- Warning: Date.prototype.toLocaleFormat is deprecated
- Warning: JavaScript 1.6's for-each-in loops are deprecated
- Warning: String.x is deprecated; use String.prototype.x instead
- Warning: expression closures are deprecated
- Warning: unreachable code after return statement
- JavaScript technologies overview
- Lexical grammar
- Enumerability and ownership of properties
- Iteration protocols
- Transitioning to strict mode
- Template literals
- Deprecated features
- ECMAScript 2015 support in Mozilla
- ECMAScript 5 support in Mozilla
- ECMAScript Next support in Mozilla
- Firefox JavaScript changelog
- New in JavaScript 1.1
- New in JavaScript 1.2
- New in JavaScript 1.3
- New in JavaScript 1.4
- New in JavaScript 1.5
- New in JavaScript 1.6
- New in JavaScript 1.7
- New in JavaScript 1.8
- New in JavaScript 1.8.1
- New in JavaScript 1.8.5
- Documentation:
- All pages index
- Methods index
- Properties index
- Pages tagged "JavaScript"
- JavaScript doc status
- The MDN project
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.
What alternatives are there for C/C++ assignment operator (=) and equality operators (==) syntax?
C/C++ use = for assignment and == for equality comparision. For example, a snippet in C++ can be like this:
But this can lead to unwanted bugs when programmers accidentally make a typo. Consider this example:
This is a (very) common typo in C/C++, partly because the two operators are so similar.
So what are the alternatives?
- language-design
![assignment operator not equal kaya3's user avatar](https://i.sstatic.net/0pja9.png?s=64)
- 4 $\begingroup$ Whatever syntax you choose for these, you can prevent this exact mistake by not having assignment expressions at all. nuclear_code = 1234; can be a statement without nuclear_code = 1234 needing to be allowed as an expression; Python did this before eventually relenting and adding the assignment operator := . Another issue that works against C in this regard is the coercion to boolean; in Java, if(nuclear_code = 1234) would be a type error because the condition must be a boolean , not an int . $\endgroup$ – kaya3 Commented May 21, 2023 at 10:27
- $\begingroup$ @kaya3 while that is true, the C/C++ way of doing it is a separate question in itself. I think that this still need to be asked. $\endgroup$ – justANewbie Commented May 21, 2023 at 10:48
- $\begingroup$ Yes, nothing wrong with the question. Just pointing out that there are more approaches to addressing this issue than just the choice of syntax for the two operators ─ and indeed, some languages use the same syntax = for both things because the context determines whether it's a name binding or an equality check. $\endgroup$ – kaya3 Commented May 21, 2023 at 12:02
- $\begingroup$ so are you asking particularly about design strategies to prevent these kinds of mistakes? Because I don't see that represented in your title, and if you are (asking about that), it should be (represented in your title) $\endgroup$ – starball Commented May 21, 2023 at 19:03
- 3 $\begingroup$ Not syntax, but in Swift assignment expressions are of type void, so this error can't happen either. $\endgroup$ – chrysante Commented May 21, 2023 at 21:36
17 Answers 17
Just throw unicode symbols at it (the apl way).
APL uses ← for assignment and = / ≡ for equality ( = is term-wise, ≡ is for the whole array). If you can afford to just throw Unicode at the problem, sometimes it's a fun solution :) really depends on how the language is meant to be written, though.
![assignment operator not equal RubenVerg's user avatar](https://i.sstatic.net/JsN10.png?s=64)
- 1 $\begingroup$ Not just Unicode have those symbols. Some calculators' BASIC dialects use ← as assignment too, from their limited character set. $\endgroup$ – Longinus Commented May 22, 2023 at 1:52
- 1 $\begingroup$ Some dialects of Smalltalk use _ for assignment, because early versions of ASCII had an arrow at that codepoint. $\endgroup$ – Bbrk24 Commented May 22, 2023 at 4:16
- $\begingroup$ @Longinus sure, but nowadays SBCS's are basically just Unicode mappings. I'd assume modern implementations of those BASIC's just read the (potentially sbcs-encoded) file and then display it as Unicode. $\endgroup$ – RubenVerg Commented May 22, 2023 at 5:03
- $\begingroup$ I can't really tell if this answer is serious. If it is, how do you expect users to type these symbols? $\endgroup$ – chrysante Commented May 27, 2023 at 20:29
- 1 $\begingroup$ @chrysante It is completely serious. In Dyalog APL, you'd hit your APL key (backtick by default) and then [ . $\endgroup$ – RubenVerg Commented May 27, 2023 at 21:27
Distinguish Assignment and Equality by Context
Some languages use = for both assignment and equality. The way the language differentiates the two use cases is by constraining the grammar so it's obvious which context is meant.
For instance, in BASIC, there is no such thing as an "expression statement", so if you write something like x=1 on a line by itself, the only possible interpretation is that you are assigning 1 to x . The alternative interpretation of "check if x is equal to 1 and discard the result" isn't an allowed interpretation in the language. This is in contrast to a language like C where both interpretations are legal (and thus, the compiler needs an additional symbol to disambiguate the two interpretations). Some languages also use a keyword like let or set to begin an assignment statement which can also help distinguish the two.
The advantage of having only one operator for both operations is that it simplifies the language. It also means that the compiler will never misinterpret your program because of a careless error. On the other hand, it is less expressive than languages that separate out the two operations. For instance, in C++, you can assign to variables within a condition or loop. In a language like BASIC, you cannot do this which may lead to more verbose code in some cases.
Even though the OP sepcifically asks for different syntax to prevent this kind of error, I would make the case that a better approach is a semantic solution:
The reason why this error can occur in C++ (and in C for that matter) is that an assignment expression evaluates to a reference to the assigned variable ( int& in this case) and that int is implicitly convertible to bool (*). By changing either of these properties we can prevent this error.
If we forbid implicit narrowing conversions or just the implicit int -> bool conversion we are already fine. This however prevents the following common C idiom:
But I would argue that this alternative code is easier to understand and just as simple to write:
If we evaluate assignment expressions not to a reference to the assigned value but to void we also solve the problem, but this time we prevent this idiom:
However this is rarely used and confusing if not seen before, and the alternative
is not significantly more verbose (and much clearer), so I would argue that losing this idiom is also not much of a loss if not an improvement.
So in conclusion I argue that while either of the approaches solves the problem, both of them are reasonable in their on right and can prevent other possible code smells.
Also now you are free to choose whatever syntax you like without the restriction of having to solve this problem.
(*) On top of that, in clauses of if statements, also explicit conversions to bool are considered in C++. This rule exists so class authors can make conversions to bool explicit, which prevents implicit conversions from the custom type to integral types (via class X -> bool -> int ) while still allowing the class to be used as a condition in if statements, but in our case it makes matters worse.
- 1 $\begingroup$ An alternative is only forbidding raw assignment in a boolean context. Extra-parentheses are cheap enough. Also, if a , b and/or c are long and/or expressions with side-effects, the rewrite will be quite cumbersome and not actually that trivial. $\endgroup$ – Deduplicator Commented Jul 3, 2023 at 15:44
- $\begingroup$ @Deduplicator If a , b or c are complex expressions, you can store them to temporaries. That's what the compiler does under the hood if you write a nested assignment expression anyhow. I agree that forbidding raw assignment in if-conditions is also a solution, but that does not prevent the error in other boolean expressions. $\endgroup$ – chrysante Commented Jul 3, 2023 at 16:38
The Pascal way
i.e using := for assignment and = for equality check.
The example in the question can be written in Pascal as:
This is so harder to mistype the two.
- 2 $\begingroup$ Just as a note about this, := was chosen because it looked a bit like the left-arrow symbol in mathematics, ⟸, but wouldn't be confused for "less than or equal to". Prolog uses :- for a similar reason. $\endgroup$ – Pseudonym Commented May 22, 2023 at 1:02
- 5 $\begingroup$ @Pseudonym I believe the := symbol exists in mathematics as well, and has the meaning of introducing the definition for a new variable. The double arrows, on the other hand, I've never seen used for anything besides implication. Might be a case of poorly internationalized syntax, though) $\endgroup$ – abel1502 Commented May 27, 2023 at 16:26
- $\begingroup$ That's what I am doing in my programming language, AEC . $\endgroup$ – FlatAssembler Commented Jul 10, 2023 at 18:47
The GNU solution to the if(x = y) {} problem is to require double parenthesisation where only if((x = y)) {} is unambiguous. That said, to mean assignment, the = , := , <- and ← operators are common across many languages descending from C, Pascal and BASIC. Vale uses a set keyword to mean reassignment.
In languages where the concept of "(re)assignment" does not exist, like most Functional and Logical ones, it is not uncommon to see = be used both for bindings and as the equality binary operator, along with == . For instance, in a language lacking builtin mutation support, this code is unambiguous:
Some English-oriented languages, like CoffeeScript , also use a is keyword.
For completeness, are also common as inequality operators != , /= , <> , ≠ and isnt , all used in various languages.
Common Lisp
Most of the time when you need a variable, you'll use let .
There's also setf .
Equality checking looks like one of the following (depending on what exactly you want—there are more equality operators).
It's really hard to accidentally mix the two up.
Use : , like JSON
Assignment and comparison have different purposes, return values, and allowed syntactic locations. Therefore, they should be represented with bigger differences than a single extra character.
The use of : for "assignments" is already fairly common and should be familiar to users:
- JSON/object notation: uses colon to bind a value to a key.
- English: like this list, where a colon associates a value or comment with an entry.
This gives you a one-character solution for assignment, leaves = free for equality, and should be immediately clear to readers.
- $\begingroup$ : is used for assignment in K and Q. $\endgroup$ – Adám Commented Oct 11, 2023 at 21:51
It partly depends on the semantics of variables and the semantics of equality.
Some languages distinguish between intensional and extensional equality . One example of this might be a set of integers represented as a binary search tree. Two sets are intensionally equal if the trees have the same structure, but extensionally equal if the numbers in the sets are the same.
Yet other languages have different notions of equality testing that depends on whether or not they will coerce types. Does 3 == 3.0 in a dynamically typed language? Sometimes you want that and sometimes you don't.
Other languages have object identity, which is different from equality.
This is a lot of symbols for equality testing that you might need to invent! Common Lisp has four of them.
Logic languages have only one symbol = , and it means unification . Just looking at simple values like numbers for the moment, if you type X = Y , then it can mean several things:
- If X is a free variable but Y has a value already bound to it, this assigns that value to X .
- Same thing if Y is free but X is bound; this is left-assignment.
- If X and Y are both bound, then this is an equality test.
- If X and Y are both free, then this aliases the two variables together. A subsequent binding of X will automagically also bind Y .
In general, X and Y could be data structures with some bound and some unbound variables inside it, in which case the full unification algorithm is run.
![assignment operator not equal Pseudonym's user avatar](https://i.sstatic.net/7Wi05.png?s=64)
In Assembly ( mov ) or more basic languages there is a keyword for assignment, such as:
I am personally not a fan of this because I prefer punctuation as operators, but this is an option that resolves ambiguity.
Or in Assembly:
Different Spellings
Other common variations for assignment are := and (so far unmentioned) <- . JavaScript is notorious for having many different comparison operators.
Vale has the interesting variation that x = 42 is only a variable declaration, and assignment must be written set x = 42 . I find, like the author, that I also write many more dclarations than assignments.
Different Semantics
A functional language, using static single assignments, or one using linear types , allows assignment only within bindings, which can be marked with let . Alternatively, since newer languages tend to discourage mutability and assignments, you could mark assignments with set , or do both. Since is is no longer than == and be or to no longer than := or <- , this could be valid syntax:
Modern programming languages like Go use the "="/":=" for assignment and "==" for the comparison. It gives a compile time error if you mistype "=" instead of "==". Another suggestion would be to use constants when comparing, but that wouldn't solve your problem with mistyping in C++.
- $\begingroup$ Welcome to PLDI. How does your answer differ from justANewbie's answer? $\endgroup$ – Isaiah Commented May 21, 2023 at 16:03
- $\begingroup$ @Isaiah Pascal uses = for equality comparison, and Go uses == for equality comparison. The point is that Go allows = instead of := for assignment when it's not in an expression. This is also the same as Python ─ = is assignment but not an expression, := is an assignment expression, == is an equality comparison. $\endgroup$ – kaya3 Commented May 21, 2023 at 17:53
- 4 $\begingroup$ "Modern programming languages like F# use = for both bindings and equality." It's a bold move to make a blanket statement like "modern PLs do x " when they disagree with each other on how to do x . $\endgroup$ – Longinus Commented May 22, 2023 at 1:56
Coming relatively out of left field is Swift’s pattern-matching operator ~= . It’s rarely written in source, instead the result of desugaring a switch or if case statement, but you could use it instead of == for regular equality comparison if you wanted to.
![assignment operator not equal Bbrk24's user avatar](https://i.sstatic.net/nBgiq.png?s=64)
The original Smalltalk uses ← for assignment and = for equality. It also uses ↑ for return.
The original Smalltalk developed at Xerox used its own workstation developed at Xerox with its own CPU developed at Xerox and its own input devices (keyboard and mouse) developed at Xerox. Smalltalk was its own Operating System as well.
All this to say that it also had its own character set and character encoding.
When Smalltalk first was ported to other systems using the ASCII character encoding, it turned out that ASCII had the character ^ at the same code point where Smalltalk had ↑ , so all Smalltalk was rendered with ^ for return on machines that used ASCII. It still looks like an upwards arrow, so it still kind of works.
Assignment was not so lucky, though: where Smalltalk had ← , ASCII has _ , so all assignments in Smalltalk were rendered as _ in ASCII. This was somewhat unsatisfactory, so it was decided to change the language specification use := for assignment. However, some Smalltalks still accept _ even today.
- $\begingroup$ I mentioned this in a comment on another answer, but this is much more thorough (as is expected from the nature of comments). $\endgroup$ – Bbrk24 Commented Jul 6, 2023 at 17:05
Use ,= or ;=
We could already understand ,= as the += -like version of , in C-style operators. And ;= looks less confusing, if you already merge , with ; .
Most compiler have the decency to give you a warning if you use the wrong operator, or if the compiler isn't sure. For example, with a good C compiler I expect that
gives a warning. And if I really want to store 1234 and then examine whether it is zero, these compilers may allow
which tells the compiler "be quiet, I know what I'm doing".
Newer languages don't allow integers to be used as boolean values. So the first example might not compile if the = operator doesn't yield a result, or it yields an integer result which cannot be used in an "if" statement. That's assuming that
would be very rare.
You could use different pairs of tokens. := and =, or = and .eq. like FORTRAN did, or a leftarrow for assignment. The warning, and possible changed semantics, is the simplest solution. In the end, if the code you type is not the code you wanted, that's your problem.
You can raise an error
For example this code in Python is correct:
raise an error (no confusing bug like C++):
You must log in to answer this question.
Not the answer you're looking for browse other questions tagged syntax language-design ..
- Featured on Meta
- Site maintenance - Tuesday, July 23rd 2024, 8 PM - Midnight EST (3 AM - 7 AM...
- Announcing a change to the data-dump process
- Upcoming initiatives on Stack Overflow and across the Stack Exchange network...
Hot Network Questions
- Is there anyway a layperson can discern what is true news vs fake news?
- Why is the future perfect used in "This latest setback will have done nothing to quell the growing doubts about the future of the club."?
- Tried making a "poor man's" active/MOSFET rectifier. It doesn't work, and I didn't expect it to, but I don't understand why
- Why do Bell states have all real coefficients?
- Has D. Trump mentioned whether he'd be willing to debate K. Harris?
- How can a liability limitation in a contract between two parties prevent a damaged 3rd-party from taking action?
- Three kilometers (~2 miles high) tsunamis go around the Earth - what kinds of ruins are left?
- Prince Rupert's Drop Armor: How Expensive?
- Is "avoid extra null pointer risk" a reason to avoid "introduce parameter objects"?
- Defining a recurrence relation
- Which word can be used to describe either the beat or the subdivision?
- Whence comes the expression ‘’starve a cold, feed a fever?”
- How can 4 chess queens attack all empty squares on a 6x6 chessboard without attacking each other?
- Superposition principle and Small signal analysis
- Could there be another relative language of the ancient Egyptian language closer to it than the Coptic?
- Have hydraulic shift systems been developed?
- One hat's number is the sum of the other 2. How did A figure out his hat number?
- Who were the oldest US Presidential nominees?
- How to buy train ticket for bike from Udine (IT) to Villach (AT)
- Sobolev spaces are smooth? Their dual is strictly convex?
- The shortest way from A1 to B1
- Variety without a compactification whose complement is smooth
- Would auto-update policies have contained the Crowdstrike outage?
- Fantasy book series with each book being about a different colored dragon?
- Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
- Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand
- OverflowAI GenAI features for Teams
- OverflowAPI Train & fine-tune LLMs
- Labs The future of collective knowledge sharing
- About the company Visit the blog
Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Get early access and see previews of new features.
What are the differences between "=" and "<-" assignment operators?
What are the differences between the assignment operators = and <- in R?
I know that operators are slightly different, as this example shows
But is this the only difference?
- assignment-operator
- 68 As noted here the origins of the <- symbol come from old APL keyboards that actually had a single <- key on them. – joran Commented Dec 12, 2014 at 17:35
9 Answers 9
The difference in assignment operators is clearer when you use them to set an argument value in a function call. For example:
In this case, x is declared within the scope of the function, so it does not exist in the user workspace.
In this case, x is declared in the user workspace, so you can use it after the function call has been completed.
There is a general preference among the R community for using <- for assignment (other than in function signatures) for compatibility with (very) old versions of S-Plus. Note that the spaces help to clarify situations like
Most R IDEs have keyboard shortcuts to make <- easier to type. Ctrl + = in Architect, Alt + - in RStudio ( Option + - under macOS), Shift + - (underscore) in emacs+ESS.
If you prefer writing = to <- but want to use the more common assignment symbol for publicly released code (on CRAN, for example), then you can use one of the tidy_* functions in the formatR package to automatically replace = with <- .
The answer to the question "Why does x <- y = 5 throw an error but not x <- y <- 5 ?" is "It's down to the magic contained in the parser". R's syntax contains many ambiguous cases that have to be resolved one way or another. The parser chooses to resolve the bits of the expression in different orders depending on whether = or <- was used.
To understand what is happening, you need to know that assignment silently returns the value that was assigned. You can see that more clearly by explicitly printing, for example print(x <- 2 + 3) .
Secondly, it's clearer if we use prefix notation for assignment. So
The parser interprets x <- y <- 5 as
We might expect that x <- y = 5 would then be
but actually it gets interpreted as
This is because = is lower precedence than <- , as shown on the ?Syntax help page.
![assignment operator not equal Richie Cotton's user avatar](https://i.sstatic.net/SkRN3.jpg?s=64)
- 14 This is also mentioned in chapter 8.2.26 of The R Inferno by Patrick Burns (Not me but a recommendation anyway) – Uwe Commented Jun 14, 2016 at 9:17
- 6 I just realised that your explanation of how x <- x = 5 gets interpreted is slightly wrong: In reality, R interprets it as `<-<-`(x, y = 5, value = 5) (which itself is more or less equivalent to tmp <- x; x <- `<-<-`(tmp, y = 5, value = 5) ). Yikes! – Konrad Rudolph Commented Jul 27, 2018 at 11:25
- 13 … And I just realised that the very first part of this answer is incorrect and, unfortunately, quite misleading because it perpetuates a common misconception: The way you use = in a function call does not perform assignment , and isn’t an assignment operator. It’s an entirely distinct parsed R expression, which just happens to use the same character. Further, the code you show does not “declare” x in the scope of the function. The function declaration performs said declaration. The function call doesn’t (it gets a bit more complicated with named ... arguments). – Konrad Rudolph Commented Apr 12, 2019 at 10:33
- 1 @ClarkThomborson The semantics are fundamentally different because in R assignment is a regular operation which is performed via a function call to an assignment function. However, this is not the case for = in an argument list. In an argument list, = is an arbitrary separator token which is no longer present after parsing. After parsing f(x = 1) , R sees (essentially) call("f", 1) . Whereas for x = 1 R sees call("=", "x", 1) . It's true that in both cases name binding also happens but, for the assignment operator, it happens after calling the assignment operator function. – Konrad Rudolph Commented Jan 12, 2023 at 15:35
- 2 @JAQuent, the intention wasn't that the expression median(x = 1:10) errors. It is to contrast it to side-effect of median(x <- 1:10) , which creates an assignment in the parent frame. Perhaps a bit subtle, but after the median(...) statements there is an x and that is what generates the error. After running median(x = 1:10) there is no x in the global environment (in this case), so evaluating x errors. – LMc Commented Jun 28 at 20:56
As your example shows, = and <- have slightly different operator precedence (which determines the order of evaluation when they are mixed in the same expression). In fact, ?Syntax in R gives the following operator precedence table, from highest to lowest:
… ‘-> ->>’ rightwards assignment ‘<- <<-’ assignment (right to left) ‘=’ assignment (right to left) …
Since you were asking about the assignment operators : yes, that is the only difference. However, you would be forgiven for believing otherwise. Even the R documentation of ?assignOps claims that there are more differences:
The operator <- can be used anywhere, whereas the operator = is only allowed at the top level (e.g., in the complete expression typed at the command prompt) or as one of the subexpressions in a braced list of expressions.
Let’s not put too fine a point on it: the R documentation is wrong . This is easy to show: we just need to find a counter-example of the = operator that isn’t (a) at the top level, nor (b) a subexpression in a braced list of expressions (i.e. {…; …} ). — Without further ado:
Clearly we’ve performed an assignment, using = , outside of contexts (a) and (b). So, why has the documentation of a core R language feature been wrong for decades?
It’s because in R’s syntax the symbol = has two distinct meanings that get routinely conflated (even by experts, including in the documentation cited above):
- The first meaning is as an assignment operator . This is all we’ve talked about so far.
- The second meaning isn’t an operator but rather a syntax token that signals named argument passing in a function call. Unlike the = operator it performs no action at runtime, it merely changes the way an expression is parsed.
So how does R decide whether a given usage of = refers to the operator or to named argument passing? Let’s see.
In any piece of code of the general form …
… the = is the token that defines named argument passing: it is not the assignment operator. Furthermore, = is entirely forbidden in some syntactic contexts:
Any of these will raise an error “unexpected '=' in ‹bla›”.
In any other context, = refers to the assignment operator call. In particular, merely putting parentheses around the subexpression makes any of the above (a) valid, and (b) an assignment . For instance, the following performs assignment:
Now you might object that such code is atrocious (and you may be right). But I took this code from the base::file.copy function (replacing <- with = ) — it’s a pervasive pattern in much of the core R codebase.
The original explanation by John Chambers , which the the R documentation is probably based on, actually explains this correctly:
[ = assignment is] allowed in only two places in the grammar: at the top level (as a complete program or user-typed expression); and when isolated from surrounding logical structure, by braces or an extra pair of parentheses.
In sum, by default the operators <- and = do the same thing. But either of them can be overridden separately to change its behaviour. By contrast, <- and -> (left-to-right assignment), though syntactically distinct, always call the same function. Overriding one also overrides the other. Knowing this is rarely practical but it can be used for some fun shenanigans .
- 5 About the precedence, and errors in R's doc, the precedence of ? is actually right in between = and <- , which has important consequences when overriding ? , and virtually none otherwise. – moodymudskipper Commented Jan 10, 2020 at 0:12
- 2 @Moody_Mudskipper that’s bizarre! You seem to be right, but according to the source code ( main/gram.y ), the precedence of ? is correctly documented, and is lower than both = and <- . – Konrad Rudolph Commented Jan 10, 2020 at 10:13
- 2 I like your explanation of R semantics... which I'd rephrase as follows. The "=" operator is overloaded. Its base semantics is to bind a formal name to an actual parameter in the arglist of a function call. In most (but not all!) contexts outside a function call, it has the same semantics as "<-": it binds a name to an existing object (or to a constant value), with copy-on-write semantics, with the side-effect of defining this name if it is currently undefined. In a few contexts, it is bound to stop() to warn naive or careless users who confuse it with the "==" operator. – Clark Thomborson Commented Nov 24, 2022 at 2:50
- 2 @ClarkThomborson I don't agree with calling one of the meanings the "base" semantics, because this implies a hierarchy that doesn't exist. And I think it's confusing to call = an overloaded operator, as well: the term "operator" in R has (until R 4.0, at least!) a specific meaning referring to a function call with special syntactic rules. This isn't what = is doing when used to bind a name to an parameter name inside a function call argument list. There's no call happening, so = in this context is just a syntactic token (like ; ), not an operator. – Konrad Rudolph Commented Nov 24, 2022 at 10:17
- 2 @ClarkThomborson Regardless of whether you find it helpful, that's precisely what it is: the syntactic = token for named parameters completely vanishes after the parsing phase, it isn't represented in the parse tree at all, nor is it evaluated. Name binding in assignment and in function calling happens fundamentally differently in R (and, to varying extents, in other languages), it isn't merely a "temporal distinction", nor is it due to operator precedence. – Konrad Rudolph Commented Nov 24, 2022 at 15:33
Google's R style guide simplifies the issue by prohibiting the "=" for assignment. Not a bad choice.
https://google.github.io/styleguide/Rguide.xml
The R manual goes into nice detail on all 5 assignment operators.
http://stat.ethz.ch/R-manual/R-patched/library/base/html/assignOps.html
![assignment operator not equal xxfelixxx's user avatar](https://i.sstatic.net/s4Pcu.jpg?s=64)
- 14 Note that any non-0 is considered TRUE by R. So if you intend to test if x is less than -y , you might write if (x<-y) which will not warn or error, and appear to work fine. It'll only be FALSE when y=0 , though. – Matt Dowle Commented Jun 8, 2012 at 15:21
- 53 Why hurt your eyes and finger with <- if you can use = ? In 99.99% of times = is fine. Sometimes you need <<- though, which is a different history. – Fernando Commented Oct 9, 2013 at 1:22
- 2 Besides the 0.01% which it won't work is just bad unreadable, hacky shortcut code for anyone who is not R only. It is just like doing bitshift to do a half division just to look smart (but you are not). My opinion is that R should deprecate the <- operator. – caiohamamura Commented Oct 31, 2023 at 13:36
x = y = 5 is equivalent to x = (y = 5) , because the assignment operators "group" right to left, which works. Meaning: assign 5 to y , leaving the number 5; and then assign that 5 to x .
This is not the same as (x = y) = 5 , which doesn't work! Meaning: assign the value of y to x , leaving the value of y ; and then assign 5 to, umm..., what exactly?
When you mix the different kinds of assignment operators, <- binds tighter than = . So x = y <- 5 is interpreted as x = (y <- 5) , which is the case that makes sense.
Unfortunately, x <- y = 5 is interpreted as (x <- y) = 5 , which is the case that doesn't work!
See ?Syntax and ?assignOps for the precedence (binding) and grouping rules.
- This was a succinct answer that hit the nail on the head! – BroVic Commented Jun 4, 2023 at 16:03
According to John Chambers, the operator = is only allowed at "the top level," which means it is not allowed in control structures like if , making the following programming error illegal.
As he writes, "Disallowing the new assignment form [=] in control expressions avoids programming errors (such as the example above) that are more likely with the equal operator than with other S assignments."
You can manage to do this if it's "isolated from surrounding logical structure, by braces or an extra pair of parentheses," so if ((x = 0)) 1 else x would work.
See http://developer.r-project.org/equalAssign.html
![assignment operator not equal Aaron left Stack Overflow's user avatar](https://i.sstatic.net/7TfIt.jpg?s=64)
From the official R documentation :
The operators <- and = assign into the environment in which they are evaluated. The operator <- can be used anywhere, whereas the operator = is only allowed at the top level (e.g., in the complete expression typed at the command prompt) or as one of the subexpressions in a braced list of expressions.
- 12 I think "top level" means at the statement level, rather than the expression level. So x <- 42 on its own is a statement; in if (x <- 42) {} it would be an expression, and isn't valid. To be clear, this has nothing to do with whether you are in the global environment or not. – Steve Pitchers Commented Sep 16, 2014 at 9:58
- 1 This: “the operator = is only allowed at the top level” is a widely held misunderstanding and completely wrong. – Konrad Rudolph Commented Mar 2, 2017 at 14:20
- This is not true - for example, this works, even though assignment is not a complete expression: 1 + (x = 2) – Pavel Minaev Commented Mar 5, 2017 at 22:52
- 1 To clarify the comments by KonradRudolph and PavelMinaev, I think it's too strong to say that it's completely wrong, but there is an exception, which is when it's "isolated from surrounding logical structure, by braces or an extra pair of parentheses." – Aaron left Stack Overflow Commented Oct 15, 2019 at 13:57
- 1 Or in function() x = 1 , repeat x = 1 , if (TRUE) x = 1 .... – moodymudskipper Commented Jan 10, 2020 at 0:18
This may also add to understanding of the difference between those two operators:
For the first element R has assigned values and proper name, while the name of the second element looks a bit strange.
R version 3.3.2 (2016-10-31); macOS Sierra 10.12.1
I am not sure if Patrick Burns book R inferno has been cited here where in 8.2.26 = is not a synonym of <- Patrick states "You clearly do not want to use '<-' when you want to set an argument of a function.". The book is available at https://www.burns-stat.com/documents/books/the-r-inferno/
- 2 Yup, it has been mentioned . But the question is about the assignment operator , whereas your excerpt concerns the syntax for passing arguments. It should be made clear (because there’s substantial confusion surrounding this point) that this is not the assignment operator. – Konrad Rudolph Commented Sep 6, 2021 at 17:27
There are some differences between <- and = in the past version of R or even the predecessor language of R (S language). But currently, it seems using = only like any other modern language (python, java) won't cause any problem. You can achieve some more functionality by using <- when passing a value to some augments while also creating a global variable at the same time but it may have weird/unwanted behavior like in
Highly recommended! Try to read this article which is the best article that tries to explain the difference between those two: Check https://colinfay.me/r-assignment/
Also, think about <- as a function that invisibly returns a value.
See: https://adv-r.hadley.nz/functions.html
- Unfortuantely Colin Fay’s article (and now your answer) repeats the common misconception about the alleged difference between = and <- . The explanation is therefore incorrect. See my answer for an exhaustive correction of this pernicious falsehood. To make it explicit: you can rewrite your first code to use = instead of <- without changing its meaning: df <- data.frame(a = rnorm(10), (b = rnorm(10))) . And just like <- , =` is a function that invisibly returns a value. – Konrad Rudolph Commented Jan 14, 2023 at 19:04
- @Konrad Rudolph R uses some rules/principles when designing the language and code interpretation for efficiency and usability that not saw in other languages. I believe most people who ask the difference between = and <- is curious about why R has more than one assignment operator compared with other popular Science/math language such as Python. And whether I can safely just only use one = like in other languages. Besides, ( is also a function in R so technically (b = rnorm(10)) is not the same as b <- rnorm(10) since you can override the meaning of ( function in codes. – Chunhui Gu Commented Jan 15, 2023 at 0:42
- Yes that’s all true but what does this have to do with my comment? The answer to “why” is: “purely historical”, and the answer to “can I just use = ” is “yes”. Everything else, in particular your claim that = can’t be used in some cases, is incorrect . Yes, of course you can override ( , just like you can override = and <- so, yes, technically you can redefine them so that they are no longer identical. But surely you agree that this is a pure distraction. – Konrad Rudolph Commented Jan 15, 2023 at 11:27
Not the answer you're looking for? Browse other questions tagged r assignment-operator r-faq or ask your own question .
- Featured on Meta
- Announcing a change to the data-dump process
- Site maintenance - Tuesday, July 23rd 2024, 8 PM - Midnight EST (3 AM - 7 AM...
- What makes a homepage useful for logged-in users
Hot Network Questions
- Particles and fields
- FDA regulation of end user non-medical software
- Tiny worms in blackberries
- Superposition principle and Small signal analysis
- Is there any way for a character to identify another character's class?
- "One-time discount" fraud: is any crime committed?
- Why the will to power?
- Applying a voltage by DAC to a Feedback pin of a DC-DC controller
- Limited list of words for a text or glyph-based messaging system
- The shortest way from A1 to B1
- Confusion about what is treated as the "reference" level in GAM using by= ordered factor in smooth
- How to disconnect the supply line from these older bathroom faucets?
- Beginner's question: proper way to handle hyphenation of words of short length?
- Passphrase generator using German word list and Python's "secrets.choice()" to select from the list. Are those strong passphrases?
- How did the NES's RP2A03 noise generator generator produce 32k bit long sequences despite only being 15 bits wide?
- Probability for a random variable to exceed its expectation
- EMI shields: When to use 2-piece cap+frame, just a frame, or just a shield (or just a cap)?
- Is there any way to save an inbred human population that also happens to be the last one left?
- How to calculate FX Forward Rate to fit bloomberg
- Braille-based Base64
- How deep should I check references of a papers I am going to cite?
- Why do Bell states have all real coefficients?
- Tried making a "poor man's" active/MOSFET rectifier. It doesn't work, and I didn't expect it to, but I don't understand why
- Can 'as much as' be replaced by 'as well as' in 'Sam retorted that it was my fault as much as his.'?
Java Tutorial
Java methods, java classes, java file handling, java how to's, java reference, java examples, java operators.
Operators are used to perform operations on variables and values.
In the example below, we use the + operator to add together two values:
Try it Yourself »
Although the + operator is often used to add together two values, like in the example above, it can also be used to add together a variable and a value, or a variable and another variable:
Java divides the operators into the following groups:
- Arithmetic operators
- Assignment operators
- Comparison operators
- Logical operators
- Bitwise operators
Arithmetic Operators
Arithmetic operators are used to perform common mathematical operations.
Operator | Name | Description | Example | Try it |
---|---|---|---|---|
+ | Addition | Adds together two values | x + y | |
- | Subtraction | Subtracts one value from another | x - y | |
* | Multiplication | Multiplies two values | x * y | |
/ | Division | Divides one value by another | x / y | |
% | Modulus | Returns the division remainder | x % y | |
++ | Increment | Increases the value of a variable by 1 | ++x | |
-- | Decrement | Decreases the value of a variable by 1 | --x |
Advertisement
Java Assignment Operators
Assignment operators are used to assign values to variables.
In the example below, we use the assignment operator ( = ) to assign the value 10 to a variable called x :
The addition assignment operator ( += ) adds a value to a variable:
A list of all assignment operators:
Operator | Example | Same As | Try it |
---|---|---|---|
= | x = 5 | x = 5 | |
+= | x += 3 | x = x + 3 | |
-= | x -= 3 | x = x - 3 | |
*= | x *= 3 | x = x * 3 | |
/= | x /= 3 | x = x / 3 | |
%= | x %= 3 | x = x % 3 | |
&= | x &= 3 | x = x & 3 | |
|= | x |= 3 | x = x | 3 | |
^= | x ^= 3 | x = x ^ 3 | |
>>= | x >>= 3 | x = x >> 3 | |
<<= | x <<= 3 | x = x << 3 |
Java Comparison Operators
Comparison operators are used to compare two values (or variables). This is important in programming, because it helps us to find answers and make decisions.
The return value of a comparison is either true or false . These values are known as Boolean values , and you will learn more about them in the Booleans and If..Else chapter.
In the following example, we use the greater than operator ( > ) to find out if 5 is greater than 3:
Operator | Name | Example | Try it |
---|---|---|---|
== | Equal to | x == y | |
!= | Not equal | x != y | |
> | Greater than | x > y | |
< | Less than | x < y | |
>= | Greater than or equal to | x >= y | |
<= | Less than or equal to | x <= y |
Java Logical Operators
You can also test for true or false values with logical operators.
Logical operators are used to determine the logic between variables or values:
Operator | Name | Description | Example | Try it |
---|---|---|---|---|
&& | Logical and | Returns true if both statements are true | x < 5 && x < 10 | |
|| | Logical or | Returns true if one of the statements is true | x < 5 || x < 4 | |
! | Logical not | Reverse the result, returns false if the result is true | !(x < 5 && x < 10) |
Java Bitwise Operators
Bitwise operators are used to perform binary logic with the bits of an integer or long integer.
Operator | Description | Example | Same as | Result | Decimal |
---|---|---|---|---|---|
& | AND - Sets each bit to 1 if both bits are 1 | 5 & 1 | 0101 & 0001 | 0001 | 1 |
| | OR - Sets each bit to 1 if any of the two bits is 1 | 5 | 1 | 0101 | 0001 | 0101 | 5 |
~ | NOT - Inverts all the bits | ~ 5 | ~0101 | 1010 | 10 |
^ | XOR - Sets each bit to 1 if only one of the two bits is 1 | 5 ^ 1 | 0101 ^ 0001 | 0100 | 4 |
<< | Zero-fill left shift - Shift left by pushing zeroes in from the right and letting the leftmost bits fall off | 9 << 1 | 1001 << 1 | 0010 | 2 |
>> | Signed right shift - Shift right by pushing copies of the leftmost bit in from the left and letting the rightmost bits fall off | 9 >> 1 | 1001 >> 1 | 1100 | 12 |
>>> | Zero-fill right shift - Shift right by pushing zeroes in from the left and letting the rightmost bits fall off | 9 >>> 1 | 1001 >>> 1 | 0100 | 4 |
Note: The Bitwise examples above use 4-bit unsigned examples, but Java uses 32-bit signed integers and 64-bit signed long integers. Because of this, in Java, ~5 will not return 10. It will return -6. ~00000000000000000000000000000101 will return 11111111111111111111111111111010
In Java, 9 >> 1 will not return 12. It will return 4. 00000000000000000000000000001001 >> 1 will return 00000000000000000000000000000100
Test Yourself With Exercises
Multiply 10 with 5 , and print the result.
Start the Exercise
![assignment operator not equal Get Certified](https://www.w3schools.com/images/img_summersale24_up_300.png)
COLOR PICKER
![assignment operator not equal colorpicker](https://www.w3schools.com/images/colorpicker2000.png)
Contact Sales
If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: [email protected]
Report Error
If you want to report an error, or if you want to make a suggestion, send us an e-mail: [email protected]
Top Tutorials
Top references, top examples, get certified.
- Python Basics
- Interview Questions
- Python Quiz
- Popular Packages
- Python Projects
- Practice Python
- AI With Python
- Learn Python3
- Python Automation
- Python Web Dev
- DSA with Python
- Python OOPs
- Dictionaries
- Python Operators
- Precedence and Associativity of Operators in Python
- Python Arithmetic Operators
- Difference between / vs. // operator in Python
- Python - Star or Asterisk operator ( * )
- What does the Double Star operator mean in Python?
- Division Operators in Python
- Modulo operator (%) in Python
- Python Logical Operators
- Python OR Operator
- Difference between 'and' and '&' in Python
- not Operator in Python | Boolean Logic
- Ternary Operator in Python
- Python Bitwise Operators
Python Assignment Operators
Assignment operators in python.
- Walrus Operator in Python 3.8
- Increment += and Decrement -= Assignment Operators in Python
- Merging and Updating Dictionary Operators in Python 3.9
- New '=' Operator in Python3.8 f-string
Python Relational Operators
- Comparison Operators in Python
- Python NOT EQUAL operator
- Difference between == and is operator in Python
- Chaining comparison operators in Python
- Python Membership and Identity Operators
- Difference between != and is not operator in Python
The Python Operators are used to perform operations on values and variables. These are the special symbols that carry out arithmetic, logical, and bitwise computations. The value the operator operates on is known as the Operand. Here, we will cover Different Assignment operators in Python .
Operators |
| ||
---|---|---|---|
| = | Assign the value of the right side of the expression to the left side operand | c = a + b |
| += | Add right side operand with left side operand and then assign the result to left operand | a += b |
| -= | Subtract right side operand from left side operand and then assign the result to left operand | a -= b |
| *= | Multiply right operand with left operand and then assign the result to the left operand | a *= b |
| /= | Divide left operand with right operand and then assign the result to the left operand | a /= b |
| %= | Divides the left operand with the right operand and then assign the remainder to the left operand | a %= b |
| //= | Divide left operand with right operand and then assign the value(floor) to left operand | a //= b |
| **= | Calculate exponent(raise power) value using operands and then assign the result to left operand | a **= b |
| &= | Performs Bitwise AND on operands and assign the result to left operand | a &= b |
| |= | Performs Bitwise OR on operands and assign the value to left operand | a |= b |
| ^= | Performs Bitwise XOR on operands and assign the value to left operand | a ^= b |
| >>= | Performs Bitwise right shift on operands and assign the result to left operand | a >>= b |
| <<= | Performs Bitwise left shift on operands and assign the result to left operand | a <<= b |
| := | Assign a value to a variable within an expression | a := exp |
Here are the Assignment Operators in Python with examples.
Assignment Operator
Assignment Operators are used to assign values to variables. This operator is used to assign the value of the right side of the expression to the left side operand.
Addition Assignment Operator
The Addition Assignment Operator is used to add the right-hand side operand with the left-hand side operand and then assigning the result to the left operand.
Example: In this code we have two variables ‘a’ and ‘b’ and assigned them with some integer value. Then we have used the addition assignment operator which will first perform the addition operation and then assign the result to the variable on the left-hand side.
S ubtraction Assignment Operator
The Subtraction Assignment Operator is used to subtract the right-hand side operand from the left-hand side operand and then assigning the result to the left-hand side operand.
Example: In this code we have two variables ‘a’ and ‘b’ and assigned them with some integer value. Then we have used the subtraction assignment operator which will first perform the subtraction operation and then assign the result to the variable on the left-hand side.
M ultiplication Assignment Operator
The Multiplication Assignment Operator is used to multiply the right-hand side operand with the left-hand side operand and then assigning the result to the left-hand side operand.
Example: In this code we have two variables ‘a’ and ‘b’ and assigned them with some integer value. Then we have used the multiplication assignment operator which will first perform the multiplication operation and then assign the result to the variable on the left-hand side.
D ivision Assignment Operator
The Division Assignment Operator is used to divide the left-hand side operand with the right-hand side operand and then assigning the result to the left operand.
Example: In this code we have two variables ‘a’ and ‘b’ and assigned them with some integer value. Then we have used the division assignment operator which will first perform the division operation and then assign the result to the variable on the left-hand side.
M odulus Assignment Operator
The Modulus Assignment Operator is used to take the modulus, that is, it first divides the operands and then takes the remainder and assigns it to the left operand.
Example: In this code we have two variables ‘a’ and ‘b’ and assigned them with some integer value. Then we have used the modulus assignment operator which will first perform the modulus operation and then assign the result to the variable on the left-hand side.
F loor Division Assignment Operator
The Floor Division Assignment Operator is used to divide the left operand with the right operand and then assigs the result(floor value) to the left operand.
Example: In this code we have two variables ‘a’ and ‘b’ and assigned them with some integer value. Then we have used the floor division assignment operator which will first perform the floor division operation and then assign the result to the variable on the left-hand side.
Exponentiation Assignment Operator
The Exponentiation Assignment Operator is used to calculate the exponent(raise power) value using operands and then assigning the result to the left operand.
Example: In this code we have two variables ‘a’ and ‘b’ and assigned them with some integer value. Then we have used the exponentiation assignment operator which will first perform exponent operation and then assign the result to the variable on the left-hand side.
Bitwise AND Assignment Operator
The Bitwise AND Assignment Operator is used to perform Bitwise AND operation on both operands and then assigning the result to the left operand.
Example: In this code we have two variables ‘a’ and ‘b’ and assigned them with some integer value. Then we have used the bitwise AND assignment operator which will first perform Bitwise AND operation and then assign the result to the variable on the left-hand side.
Bitwise OR Assignment Operator
The Bitwise OR Assignment Operator is used to perform Bitwise OR operation on the operands and then assigning result to the left operand.
Example: In this code we have two variables ‘a’ and ‘b’ and assigned them with some integer value. Then we have used the bitwise OR assignment operator which will first perform bitwise OR operation and then assign the result to the variable on the left-hand side.
Bitwise XOR Assignment Operator
The Bitwise XOR Assignment Operator is used to perform Bitwise XOR operation on the operands and then assigning result to the left operand.
Example: In this code we have two variables ‘a’ and ‘b’ and assigned them with some integer value. Then we have used the bitwise XOR assignment operator which will first perform bitwise XOR operation and then assign the result to the variable on the left-hand side.
Bitwise Right Shift Assignment Operator
The Bitwise Right Shift Assignment Operator is used to perform Bitwise Right Shift Operation on the operands and then assign result to the left operand.
Example: In this code we have two variables ‘a’ and ‘b’ and assigned them with some integer value. Then we have used the bitwise right shift assignment operator which will first perform bitwise right shift operation and then assign the result to the variable on the left-hand side.
Bitwise Left Shift Assignment Operator
The Bitwise Left Shift Assignment Operator is used to perform Bitwise Left Shift Opertator on the operands and then assign result to the left operand.
Example: In this code we have two variables ‘a’ and ‘b’ and assigned them with some integer value. Then we have used the bitwise left shift assignment operator which will first perform bitwise left shift operation and then assign the result to the variable on the left-hand side.
Walrus Operator
The Walrus Operator in Python is a new assignment operator which is introduced in Python version 3.8 and higher. This operator is used to assign a value to a variable within an expression.
Example: In this code, we have a Python list of integers. We have used Python Walrus assignment operator within the Python while loop . The operator will solve the expression on the right-hand side and assign the value to the left-hand side operand ‘x’ and then execute the remaining code.
Please Login to comment...
Similar reads.
- Python-Operators
Improve your Coding Skills with Practice
What kind of Experience do you want to share?
![](http://nandemo.space/777/templates/cheerup1/res/banner1.gif)
IMAGES
VIDEO
COMMENTS
The " = " is an assignment operator used to assign the value on the right to the variable on the left. For example: Example: == operator. The '==' operator checks whether the two given operands are equal or not. If so, it returns true. Otherwise it returns false. For example:
The assignment operator is completely different from the equals (=) sign used as syntactic separators in other locations, which include:Initializers of var, let, and const declarations; Default values of destructuring; Default parameters; Initializers of class fields; All these places accept an assignment expression on the right-hand side of the =, so if you have multiple equals signs chained ...
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 ...
The = operator is an assignment operator. You are assigning an object to a value. The == operator is a conditional equality operation. You are confirming whether two things have equal values. There is also a === operator. This compares not only value, but also type. Assignment Operators. Comparison Operators
An assignment operator assigns a value to its left operand based on the value of its right operand. The simple assignment operator is equal (=), which assigns the value of its right operand to its left operand.That is, x = f() is an assignment expression that assigns the value of f() to x. There are also compound assignment operators that are shorthand for the operations listed in the ...
The Addition Assignment Operator (+=) adds a value to a variable. Assignment. ... not equal value or not equal type > greater than < less than >= greater than or equal to <= less than or equal to? ternary operator: Note. Comparison operators are fully described in the JS Comparisons chapter.
The assignment operator (operator =, with one equal sign) is not the same as the equality comparison operator (operator ==, with two equal signs); the first one (=) assigns the value on the right-hand to the variable on its left, while the other (==) compares whether the values on both sides of the operator are equal.
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.
In this article. The assignment operator = assigns the value of its right-hand operand to a variable, a property, or an indexer element given by its left-hand operand. The result of an assignment expression is the value assigned to the left-hand operand. The type of the right-hand operand must be the same as the type of the left-hand operand or ...
The strict inequality operator checks whether its operands are not equal. It is the negation of the strict equality operator so the following two lines will always give the same result: js. x !== y; !(x === y); For details of the comparison algorithm, see the page for the strict equality operator. Like the strict equality operator, the strict ...
Comparison operators are used to compare two values (or variables). This is important in programming, because it helps us to find answers and make decisions. The return value of a comparison is either 1 or 0, which means true ( 1) or false ( 0 ). These values are known as Boolean values, and you will learn more about them in the Booleans and If ...
The equality operator returns true or false based on whether the operands (the values being compared) are equal. For example, the following code will return false: let x = 5; // declares x and assigns x to the value 5. x == 8; // returns false. Interestingly, if we compare an integer 5 and a string "5" it returns true.
The simple assignment operator is equal (=), which assigns the value of its right operand to its left operand. That is, x = y assigns the value of y to x. There are also compound assignment operators that are shorthand for the operations listed in the following table: Compound assignment operators; Name Shorthand operator Meaning;
In languages where the concept of "(re)assignment" does not exist, like most Functional and Logical ones, ... Two sets are intensionally equal if the trees have the same structure, but extensionally equal if the numbers in the sets are the same. ... So the first example might not compile if the = operator doesn't yield a result, or it yields an ...
The difference in assignment operators is clearer when you use them to set an argument value in a function call. For example: median(x = 1:10) x. ## Error: object 'x' not found. In this case, x is declared within the scope of the function, so it does not exist in the user workspace. median(x <- 1:10)
variable operator value; Types of Assignment Operators in Java. The Assignment Operator is generally of two types. They are: 1. Simple Assignment Operator: The Simple Assignment Operator is used with the "=" sign where the left side consists of the operand and the right side consists of a value. The value of the right side must be of the same data type that has been defined on the left side.
Basic keywords and general expressions in JavaScript. These expressions have the highest precedence (higher than operators ). The this keyword refers to a special property of an execution context. Basic null, boolean, number, and string literals. Array initializer/literal syntax. Object initializer/literal syntax.
Java Comparison Operators. Comparison operators are used to compare two values (or variables). This is important in programming, because it helps us to find answers and make decisions. The return value of a comparison is either true or false. These values are known as Boolean values, and you will learn more about them in the Booleans and If ...
No assignment is performed if the left-hand side is not nullish, due to short-circuiting of the nullish coalescing operator. For example, the following does not throw an error, despite x being const :
Assignment Operator. Assignment Operators are used to assign values to variables. This operator is used to assign the value of the right side of the expression to the left side operand. Python. # Assigning values using # Assignment Operator a = 3 b = 5 c = a + b # Output print(c) Output. 8.
Logical OR assignment short-circuits, meaning that x ||= y is equivalent to x || (x = y), except that the expression x is only evaluated once. No assignment is performed if the left-hand side is not falsy, due to short-circuiting of the logical OR operator. For example, the following does not throw an error, despite x being const: