The Python Assignment operator is utilized to assign a value to a variable. Rather than placing the value directly in a memory location, the variable merely references the value stored in memory. Python offers augmented assignment operators, often referred to as compound operators, which enhance the efficiency of your code. The latest Python version introduced the concept of the walrus operator, enabling assignment of values to variables within an expression. In this article, you will explore all these concepts through practical examples.
An assignment statement consists of a variable (the target), a value (the object), and the assignment operator (=), which connects the variable to the value. The assignment operator is one of the essential operators in Python.
The standard syntax for an assignment statement is
variable = expression
Examples:
name = “Alice”
age = 30
items = [10, 20, 30]
x = y = z = 0
total_cost = price * quantity + tax
def get_status(): return “active” status = get_status()
Name Binding
In Python, variables do not represent actual containers that contain a value. Instead, they are just identifiers used to point to the container that holds the value. This implies that multiple variables can serve as references to a single value.
Example:
Python
Code Copied!
var isMobile = window.innerWidth “);
editor89774.setValue(decodedContent); // Set the default text
editor89774.clearSelection();
editor89774.setOptions({
maxLines: Infinity
});
function decodeHTML89774(input) {
var doc = new DOMParser().parseFromString(input, “text/html”);
return doc.documentElement.textContent;
}
// Function to copy code to clipboard
function copyCodeToClipboard89774() {
const code = editor89774.getValue(); // Get code from the editor
navigator.clipboard.writeText(code).then(() => {
jQuery(“.maineditor89774 .copymessage”).show();
setTimeout(function() {
jQuery(“.maineditor89774 .copymessage”).hide();
}, 2000);
}).catch(err => {
console.error(“Error copying code: “, err);
});
}
function runCode89774() {
var code = editor89774.getSession().getValue();
jQuery.ajax({
url: “https://intellipaat.com/blog/wp-admin/admin-ajax.php”,
type: “post”,
data: {
language: “python”,
code: code,
cmd_line_args: “”,
variablenames: “”,
action:”compilerajax”
},
success: function(response) {
var myArray = response.split(“~”);
var data = myArray[1];
jQuery(“.output89774”).html(“
"+data+"");
jQuery(".maineditor89774 .code-editor-output").show();
jQuery("#runBtn89774 i.run-code").hide();
}
})
}
function closeoutput89774() {
var code = editor89774.getSession().getValue();
jQuery(".maineditor89774 .code-editor-output").hide();
}
// Attach event listeners to the buttons
document.getElementById("copyBtn89774").addEventListener("click", copyCodeToClipboard89774);
document.getElementById("runBtn89774").addEventListener("click", runCode89774);
document.getElementById("closeoutputBtn89774").addEventListener("click", closeoutput89774);
Output:
``````html
Clarification: In this instance, both x and y point to the identical integer object, 10.
Chained Assignment Operator in Python
Chaining an operator denotes that multiple operators can exist within the same expression. For the Assignment Operator, this allows you to designate the same value to several variables.
function closeoutput16596() {
var code = editor16596.getSession().getValue();
jQuery(".maineditor16596 .code-editor-output").hide();
}
// Attach event listeners to the buttons
document.getElementById("copyBtn16596").addEventListener("click", copyCodeToClipboard16596);
document.getElementById("runBtn16596").addEventListener("click", runCode16596);
document.getElementById("closeoutputBtn16596").addEventListener("click", closeoutput16596);
Result:
Clarification: Through the application of chained assignment, a, b, and c were assigned the identical value of 10.
Augmented Assignment Operators in Python
Augmented assignment operators, which are also referred to as compound operators, merge arithmetic and bitwise operators with the assignment operator. Utilizing an augmented operator permits you to evaluate the expression and simultaneously assign the result to the variable. This condenses two steps into one. It enhances code efficiency, especially with mutable objects, which are items that can be altered post-declaration.
Arithmetic Augmented Operators in Python
Python comprises seven arithmetic operators; consequently, there are seven augmented arithmetic operators. The assignment operator follows right-associativity, meaning that expressions are evaluated from right to left. Thus, calculations occur first, followed by the assignment of the result to the variable.
Consider x -= y as an illustration.
x -= y is tantamount to x = x – y.
Initially, x - y is computed.
Subsequently, the result is assigned to x.
Instance:
Python
Code Copied!
var isMobile = window.innerWidth ");
editor86083.setValue(decodedContent); // Initialize the default text
editor86083.clearSelection();
editor86083.setOptions({
maxLines: Infinity
});
function decodeHTML86083(input) {
var doc = new DOMParser().parseFromString(input, "text/html");
return doc.documentElement.textContent;
}
// Function to duplicate code to clipboard
function copyCodeToClipboard86083() {
const code = editor86083.getValue(); // Retrieve code from the editor
navigator.clipboard.writeText(code).then(() => {
// alert("Code successfully copied to clipboard!");
data: {
language: "python",
code: code,
cmd_line_args: "",
variablenames: "",
action:"compilerajax"
},
success: function(response) {
var myArray = response.split("~");
var data = myArray[1];
jQuery(".output86083").html("
"+data+"");
jQuery(".maineditor86083 .code-editor-output").show();
jQuery("#runBtn86083 i.run-code").hide();
}
})
}
function closeOutput86083() {
var code = editor86083.getSession().getValue();
jQuery(".maineditor86083 .code-editor-output").hide();
}
// Attach event listeners to the buttons
document.getElementById("copyBtn86083").addEventListener("click", copyCodeToClipboard86083);
document.getElementById("runBtn86083").addEventListener("click", executeCode86083);
document.getElementById("closeoutputBtn86083").addEventListener("click", closeOutput86083);
Output:
Explanation: This script displays the value of x following each arithmetic augmented assignment operation. The same concept is applicable to all of them.
Below is a table featuring all the arithmetic augmented operators.
Operator
Example
Equivalent
Description
+=
x += y
x = x + y
Add and assign
-=
x -= y
x = x – y
Subtract and assign
*=
x *= y
x = x * y
Multiply and assign
/=
x /= y
x = x / y
Divide and assign
//=
x //= y
x = x // y
Floor Divide and assign
%=
x %= y
x = x % y
Evaluate modulo and assign
**=
x **= y
x = x ** y
Calculate the exponent and assign
Bitwise Augmented Operators in Python
The bitwise augmented operators function similarly to the arithmetic operators. They consider the binary values of the operands before performing calculations. It operates under the same principle and is assessed in the same way. Let’s examine an example.
Example:
Python
Code Copied!
Result:
Clarification: In this instance, the binary representations of 10, 3, and 2 are utilized to perform the operations.
Operator
Sample
Equivalent
Description
&=
x &= y
x = x & y
Perform a bitwise AND and then assign
^=
x ^= y
x = x ^ y
Execute bitwise XOR and then assign
>>=
x >>= y
x = x >> y
Conduct Bitwise Right Shift and then assign
<<=
x <<= y
x = x << y
Execute Bitwise Left Shift and assign
Functioning of Augmented Operators in Python
Augmented operators exhibit different behavior for mutable and immutable entities in Python. Let’s explore them individually with instances.
Assignment with Immutable Entities in Python
Immutable entities cannot be altered post-declaration. In Python, immutable types include int, bool, float, str, and tuple. If an attempt is made to modify a variable linked to an immutable entity, it will simply generate a new entity at another memory location, and the variable will now point to the new entity.
Let’s clarify the process step-by-step through an example.
Suppose we set x = 8 and then alter it to 5 via x = 5.
Initially, x points to the container holding the value 8.
When you execute x = 5, it generates a new integer value at a different memory location.
x then redirects itself to this new object, ‘5’, leaving the prior object, ‘8’.
Now, the ‘8’ entity lacks any reference. The ‘8’ entity will eventually be deleted by Python’s garbage collector.
Instance:
Python
Code Successfully Copied!
Result:
``````html
Clarification: Although the action appears to alter x, it generates a new object, ‘6’, and assigns the variable x to it. The initial object ‘5’ stays intact and will eventually be removed by the garbage collector.
Assignment with Mutable Objects in Python
Mutable entities are those that can be altered post their declaration. In Python, mutable entities consist of lists, dictionaries, and sets. Augmented Operators can change the object directly. This allows it to modify the existing variable without generating a new one.
Illustration:
Python
Code Copied!
Outcome:
Clarification: As illustrated, the former object is altered without creating a new object in a different memory location.
Python Walrus Operator
This is a unique type of assignment operator introduced in Python 3.8. Walrus operators enable you to assess an expression or condition while simultaneously assigning the result using a single line of code.
The overall syntax of this operator is as below:
variable := expression
The yield of the expression is assessed and assigned to the variable. Following that, it is returned as the outcome of the entire expression.
Illustration:
Python
Code Copied!
// Code continuation...
``````html
");
editor56744.setValue(parsedContent); // Establish the default text
editor56744.clearSelection();
editor56744.setOptions({
maxLines: Infinity
});
function decodeHTML56744(input) {
var doc = new DOMParser().parseFromString(input, "text/html");
return doc.documentElement.textContent;
}
// Function to replicate code to clipboard
function copyCodeToClipboard56744() {
const code = editor56744.getValue(); // Retrieve code from the editor
navigator.clipboard.writeText(code).then(() => {
// alert("Code copied to clipboard!");
function closeOutput56744() {
var code = editor56744.getSession().getValue();
jQuery(".maineditor56744 .code-editor-output").hide();
}
// Attach event handlers to the buttons
document.getElementById("copyBtn56744").addEventListener("click", copyCodeToClipboard56744);
document.getElementById("runBtn56744").addEventListener("click", runCode56744);
document.getElementById("closeoutputBtn56744").addEventListener("click", closeOutput56744);
Output:
Explanation:
In this scenario, the expression (square := n * n) computes the square of n and assigns it to the variable square. Subsequently, the condition square > 100 is evaluated on the same line, and if the condition holds true, the value of square is added to the list.
Without utilizing the walrus operator, the square is computed first. Then, it is compared to 100 and appended to the list if the condition is satisfied.
When using the walrus operator, both actions occur concurrently. The square is computed and assigned within the condition, and if it surpasses 100, it’s included in the ‘squares’ list.
Conclusion
Assignment operators serve as a core element of Python, playing an essential role in how values are stored, modified, and managed within your program. Python implements name binding rather than regarding variables as containers. Augmented assignment operators simplify operations by combining arithmetic or bitwise computations with assignment, reducing code length and often enhancing efficiency. Additionally, you were introduced to the walrus operator (:=), a sophisticated feature that facilitates assignments in expressions, eliminating redundancy and rendering conditions more expressive and compact.
To elevate your expertise, consider this Python training course to gain practical experience. Moreover, prepare for job interviews with Python interview questions curated by industry specialists.
Python Assignment Operators – FAQs
Q1. Can assignment operators be chained in Python?
Yes, you can chain assignment operators, for example, a = b = c = 5 assigns the value of 5 to all three variables.
Q2. What distinguishes = from == in Python?
The = operator is utilized to assign values to variables, while == is used to check equality between two values.
Q3. Can the += operator modify immutable types like strings?
No, += does not alter the original string but forms a new string since strings are immutable in Python.
Q4. What happens when an assignment operator is utilized on a list in Python?
When applied to a list, assignment operators like += or *= modify the list in place, as lists are mutable objects in Python.
Q5. Is it feasible to use multiple assignment operators in a single line in Python?
Yes, you can chain several assignment operators in one line (x = y = z = 10), assigning the same value to each variable.
To provide the best experiences, we use technologies like cookies to store and/or access device information. Consenting to these technologies will allow us to process data such as browsing behavior or unique IDs on this site. Not consenting or withdrawing consent, may adversely affect certain features and functions.
Functional
Always active
The technical storage or access is strictly necessary for the legitimate purpose of enabling the use of a specific service explicitly requested by the subscriber or user, or for the sole purpose of carrying out the transmission of a communication over an electronic communications network.
Preferences
The technical storage or access is necessary for the legitimate purpose of storing preferences that are not requested by the subscriber or user.
Statistics
The technical storage or access that is used exclusively for statistical purposes.The technical storage or access that is used exclusively for anonymous statistical purposes. Without a subpoena, voluntary compliance on the part of your Internet Service Provider, or additional records from a third party, information stored or retrieved for this purpose alone cannot usually be used to identify you.
Marketing
The technical storage or access is required to create user profiles to send advertising, or to track the user on a website or across several websites for similar marketing purposes.