Python Assignment Expressions

PythonPythonBeginner
Practice Now

Introduction

In this lab, we will learn about Python Assignment Expressions, also known as the "walrus operator" (:=). This operator, introduced in Python 3.8, allows you to assign a value to a variable as part of an expression. It is particularly useful for optimizing code, avoiding redundant calculations, and simplifying complex expressions.

By the end of this lab, you should be able to understand and apply the assignment expressions in your Python programs. We will start with simple examples and gradually progress to more complex ones.

Simple Assignment Expression

In this step, we will start with a simple example to understand the basic syntax of assignment expressions.

Open the Python Shell

Open the Python shell by typing the following command in the terminal.

python3

Simple Test

Let's start with a simple example

## Basic example of an assignment expression
n = 5
result = (squared := n * n)
print(squared, result)

Output:

25 25

Here, we assign the result of n * n to the variable squared using the walrus operator := within the parentheses. Then, we assign the value of squared to the variable result. Finally, we print the values of squared and result.

Using Assignment Expressions in a Conditional Statement

In this step, we will explore the usage of assignment expressions within a conditional statement.

## Using assignment expressions in a conditional statement
input_str = "Hello, world!"
if (length := len(input_str)) > 10:
    print(f"The string has {length} characters, which is more than 10.")
else:
    print(f"The string has {length} characters, which is less than or equal to 10.")

Output:

The string has 13 characters, which is more than 10.

Here, we calculate the length of input_str and assign it to the variable length using the walrus operator within the condition of the if statement. This allows us to use the value of length in both branches of the conditional.

Using Assignment Expressions in a Loop

Now, let's see how to use assignment expressions in a loop.

## Using assignment expressions in a loop
numbers = [1, 2, 3, 4, 5]
while (n := numbers.pop()) > 2:
    print(f"Popped {n}, which is greater than 2.")
print(f"Popped {n}, which is less than or equal to 2.")

Output:

Popped 5, which is greater than 2.
Popped 4, which is greater than 2.
Popped 3, which is greater than 2.
Popped 2, which is less than or equal to 2

In this example, we use the walrus operator within the condition of the while loop to pop elements from the numbers list and assign them to the variable n. The loop continues until an element less than or equal to 2 is popped.

Using Assignment Expressions in a List Comprehension

Finally, let's explore using assignment expressions in a list comprehension.

## Using assignment expressions in a list comprehension
from math import sqrt

numbers = [1, 4, 9, 16, 25]
roots = [int(root) for n in numbers if (root := sqrt(n)) == int(root)]
print(roots)

Output:

[1, 2, 3, 4, 5]

In this example, we use the walrus operator within a list comprehension to calculate the square root of each number in numbers and check if it is an integer. If it is, we add the integer square root to the roots list.

Summary

In this lab, we explored Python Assignment Expressions (walrus operator) through a series of step-by-step examples. We covered basic syntax and usage in conditional statements, loops, and list comprehensions. By now, you should have a good understanding of how to use assignment expressions in your Python code to optimize and simplify complex expressions.

Remember to use the assignment expressions wisely to make your code more readable and efficient. As with any programming feature, it's important not to overuse it, as it may lead to less maintainable code if used excessively or inappropriately.

Keep practicing and experimenting with the walrus operator in different scenarios to improve your Python programming skills. Good luck, and happy coding!

Other Python Tutorials you may like