Generic selectors
Exact matches only
Search in title
Search in content
Post Type Selectors
Filter by Categories
About Article
Analyze Data
Archive
Best Practices
Better Outputs
Blog
Code Optimization
Code Quality
Command Line
Daily tips
Dashboard
Data Analysis & Manipulation
Data Engineer
Data Visualization
DataFrame
Delta Lake
DevOps
DuckDB
Environment Management
Feature Engineer
Git
Jupyter Notebook
LLM
LLM
Machine Learning
Machine Learning
Machine Learning & AI
Manage Data
MLOps
Natural Language Processing
NumPy
Pandas
Polars
PySpark
Python Tips
Python Utilities
Python Utilities
Scrape Data
SQL
Testing
Time Series
Tools
Visualization
Visualization & Reporting
Workflow & Automation
Workflow Automation

Walrus Operator: Assign a Variable in an Expression

Table of Contents

Walrus Operator: Assign a Variable in an Expression

The walrus operator (:=) in Python 3.8+ allows you to assign a variable in an expression, making your code more readable and efficient. It’s useful in two main scenarios:

  1. Giving a meaningful name to a complex expression for better readability.
  2. Avoiding repeated computations by reusing a variable instead of recomputing the expression.

Let’s consider an example where we want to calculate the radius, area, and volume of a circle given its diameter and height:

from math import pi

diameter = 4
height = 2

Without the walrus operator, we might compute the radius and area multiple times:

circle = {
    "radius": diameter / 2, # computed twice
    "area": pi * (diameter / 2)**2, # computed twice
    "volume": pi * (diameter / 2)**2 * height,
}
2.0

To avoid repeated computations, we can assign the radius and area to variables before creating the dictionary:

radius = diameter / 2
area = pi * radius**2

circle = {
    "radius": radius,
    "area": area,
    "volume": area * height,
}
2.0

To make the code more concise, we can use the walrus operator to assign the radius and area to variables while creating the dictionary.

circle = {
    "radius": (radius := diameter / 2),
    "area": (area := pi * radius**2),
    "volume": area * height,
}

After executing the code with the walrus operator, we can access the assigned variables:

print(radius)
print(area)
2.0
12.566370614359172

By using the walrus operator, we can simplify our code, reduce repeated computations, and improve readability.

Leave a Comment

Your email address will not be published. Required fields are marked *

0
    0
    Your Cart
    Your cart is empty
    Scroll to Top

    Work with Khuyen Tran

    Work with Khuyen Tran