DigitalOcean Referral Badge
Udit Vashisht
Author: Udit Vashisht


New Walrus Operator in Python 3.8

  • 4 minutes read
  • 167 Views
New Walrus Operator in Python 3.8

    Table of Contents

What is new walrus operator in Python 3.8?

The official version of Python 3.8 was released in October, 2019.

What’s new in Python 3.8?

Before going in details about new Walrus Operator in Python 3.8, I will like to summarize what is new in Python 3.8 :-

New Feature PEP
Assignment Expression (Walrus Operator) PEP 572
Positional-only parameters PEP 570
f-strings support = for self-documenting expressions and debugging -
importlib.metadata (New module) -
Typing PEP 586

The Walrus Operator

The new assignment operator having notation := is the biggest and the coolest change in Python 3.8. It is called the Walrus operator due to its resemblance to the eyes and tusks of a walrus.

The walrus operator allows to assign and return a value in a single expression. For example, normally you will do this

# walrus_operator.py

a_value = "Hello"
print(a_value)

# Output
Hello

However, using the walrus operator, you can do it in a single expression as under:-

# walrus_operator.py

print (a_value := "Hello")

# Output
Hello

Basically, walrus operator helps us to do certain tasks with more convenience and does not bring anything new in terms of functionality.

In the following example, using the walrus operator helps avoid using len() twice:-

# walrus_operator.py

a_list = [1, 2 , 3, 4, 5]

if (n:=len(a_list))>3:
    print(f'List is too long ({n} elements, expected <= 3)')

# Output
List is too long (5 elements, expected <= 3)

# In Python 3.7

a_list = [1, 2 , 3, 4, 5]
if len(a_list)>3:
    print(f'List is too long ({len(a_list)} elements, expected <= 3)')

# Output
List is too long (5 elements, expected <= 3)

So, in the above example using the walrus operator made our expression more convenient.

The walrus operator is also useful with while-loops that compute a value to test loop termination and then need that same value again in the body of the loop.

# walrus_operator.py

inputs = list()
while (current := input("Write something: ")) != "quit":
    inputs.append(current)

However, the official documentation cautions to limit the use of the walrus operator to clean cases that reduce complexity and improve readability.


Related Posts

How to use Python to download Historical Data of NSE Stocks?
By Udit Vashisht

Stop manually downloading the historical data of NSE stocks, use Python instead

If you are manually downloading the historical or daily data for the stocks from NSE, you should stop doing that and start using Python to do the same. There are many benefits of using Python to download historical ...

Read More
Download Latest NIFTY 50 Stocks List 2022 using Two Lines of Python Code
By Udit Vashisht

How to download latest NIFTY 50 Stocks List 2022 using just two lines of Python Code?

In this tutorial, we will use python to download the latest NIFTY 50 stocks. We will be using the official NSE website to source the link to the CSV File. Hence, this method will ...

Read More
Get an automated email on availability of Covishield and Covaxin on Cowin
By Udit Vashisht

How to get an automated email on availability of Covishield and Covaxin on Cowin website?

I have created a Python Script which can be used to send automated email if the COVID-19 Vaccine (Covishield or Covaxin) is available on the Indian Government’s Cowin Portal for any age group ...

Read More
Search
Tags
tech tutorials automate python beautifulsoup web scrapping webscrapping bs4 Strip Python3 programming Pythonanywhere free Online Hosting hindi til github today i learned Windows Installations Installation Learn Python in Hindi Python Tutorials Beginners macos installation guide linux SaralGyaan Saral Gyaan json in python JSON to CSV Convert json to csv python in hindi convert json csv in python remove background python mini projects background removal remove.bg tweepy Django Django tutorials Django for beginners Django Free tutorials Proxy Models User Models AbstractUser UserModel convert json to csv python json to csv python Variables Python cheats Quick tips == and is f string in python f-strings pep-498 formatting in python python f string smtplib python send email with attachment python send email automated emails python python send email gmail automated email sending passwords secrets environment variables if name == main Matplotlib tutorial Matplotlib lists pandas Scatter Plot Time Series Data Live plots Matplotlib Subplots Matplotlib Candlesticks plots Tutorial Logging unittest testing python test Object Oriented Programming Python OOP Database Database Migration Python 3.8 Walrus Operator Data Analysis Pandas Dataframe Pandas Series Dataframe index pandas index python pandas tutorial python pandas python pandas dataframe python f-strings padding how to flatten a nested json nested json to csv json to csv python pandas Pandas Tutorial insert rows pandas pandas append list line charts line plots in python Django proxy user model django custom user model django user model matplotlib marker size pytplot legends scatter plot python pandas python virtual environment virtualenv venv python python venv virtual environment in python python decorators bioinformatics fastafiles Fasta python list append append raspberry pi editor cron crontab Cowin Cowin api python dictionary Python basics dictionary python list list ios development listview navigationview swiftui ios mvvm swift environmentobject property wrapper @State @Environm popup @State ios15 alert automation instagram instaloader texteditor youtubeshorts textfield multi-line star rating reusable swift selenium selenium driver requests-html youtube youtube shorts python automation python tutorial algo trading nifty 50 nifty50 stock list nifty50 telegram telegram bot dictionary in Python how to learn python learn python