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.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("`Python`")) -.-> python/BasicConceptsGroup(["`Basic Concepts`"]) python(("`Python`")) -.-> python/ControlFlowGroup(["`Control Flow`"]) python(("`Python`")) -.-> python/DataStructuresGroup(["`Data Structures`"]) python(("`Python`")) -.-> python/ModulesandPackagesGroup(["`Modules and Packages`"]) python(("`Python`")) -.-> python/PythonStandardLibraryGroup(["`Python Standard Library`"]) python(("`Python`")) -.-> python/FunctionsGroup(["`Functions`"]) python/BasicConceptsGroup -.-> python/comments("`Comments`") python/BasicConceptsGroup -.-> python/variables_data_types("`Variables and Data Types`") python/BasicConceptsGroup -.-> python/numeric_types("`Numeric Types`") python/BasicConceptsGroup -.-> python/type_conversion("`Type Conversion`") python/ControlFlowGroup -.-> python/conditional_statements("`Conditional Statements`") python/ControlFlowGroup -.-> python/for_loops("`For Loops`") python/ControlFlowGroup -.-> python/while_loops("`While Loops`") python/ControlFlowGroup -.-> python/list_comprehensions("`List Comprehensions`") python/DataStructuresGroup -.-> python/lists("`Lists`") python/DataStructuresGroup -.-> python/tuples("`Tuples`") python/DataStructuresGroup -.-> python/sets("`Sets`") python/ModulesandPackagesGroup -.-> python/importing_modules("`Importing Modules`") python/ModulesandPackagesGroup -.-> python/using_packages("`Using Packages`") python/ModulesandPackagesGroup -.-> python/standard_libraries("`Common Standard Libraries`") python/PythonStandardLibraryGroup -.-> python/math_random("`Math and Random`") python/PythonStandardLibraryGroup -.-> python/data_collections("`Data Collections`") python/FunctionsGroup -.-> python/build_in_functions("`Build-in Functions`") subgraph Lab Skills python/comments -.-> lab-5002{{"`Python Assignment Expressions`"}} python/variables_data_types -.-> lab-5002{{"`Python Assignment Expressions`"}} python/numeric_types -.-> lab-5002{{"`Python Assignment Expressions`"}} python/type_conversion -.-> lab-5002{{"`Python Assignment Expressions`"}} python/conditional_statements -.-> lab-5002{{"`Python Assignment Expressions`"}} python/for_loops -.-> lab-5002{{"`Python Assignment Expressions`"}} python/while_loops -.-> lab-5002{{"`Python Assignment Expressions`"}} python/list_comprehensions -.-> lab-5002{{"`Python Assignment Expressions`"}} python/lists -.-> lab-5002{{"`Python Assignment Expressions`"}} python/tuples -.-> lab-5002{{"`Python Assignment Expressions`"}} python/sets -.-> lab-5002{{"`Python Assignment Expressions`"}} python/importing_modules -.-> lab-5002{{"`Python Assignment Expressions`"}} python/using_packages -.-> lab-5002{{"`Python Assignment Expressions`"}} python/standard_libraries -.-> lab-5002{{"`Python Assignment Expressions`"}} python/math_random -.-> lab-5002{{"`Python Assignment Expressions`"}} python/data_collections -.-> lab-5002{{"`Python Assignment Expressions`"}} python/build_in_functions -.-> lab-5002{{"`Python Assignment Expressions`"}} end

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