What Is the Walrus Operator in Python?
Before and After: Implementing the Walrus Operator

Let’s take a look at a simple use case and how we can implement the walrus operator to improve the efficiency of our code.

We’re going to check the length of a given list and print an error message that includes the length.

my_list = [1,2,3,4,5] if len(my_list) > 3:

print(f"The list is too long with {len(my_list)} elements")

In case you’re unsure about the f before the string in the print statement, that’s called a format-string literal, f-string for short.

Now, the walrus operator will eliminate calling the len() function twice.

my_list = [1,2,3,4,5] if (n := len(my_list)) > 3:

print(f"The list is too long with {n} elements")
['Jonathan Hsu']
['Software Development', 'Programming', 'Python', 'Data Science', 'Technology']