|
|
Python Walrus Operator
Author: Venkata Sudhakar
The walrus operator := (named for its resemblance to a walrus face) was added in Python 3.8. It lets you assign a value to a variable and use that value in the same expression. This is called an assignment expression. The most common use is inside a while loop or if statement where you want to both capture a value and check it in one line, avoiding a repeated call. Without the walrus operator you often have to call a function twice - once to get the value and once to check it - or use a separate assignment before the condition. The walrus operator eliminates this duplication cleanly. The below example shows the most practical uses: reading lines until empty, and filtering a list while capturing a computed value.
It gives the following output,
Read: line1
Read: line2
Read: line3
It gives the following output,
['ERROR 500', 'ERROR 404']
Use the walrus operator when it genuinely removes duplication and improves clarity. Avoid it when it makes the expression hard to read - a clear two-line version is always better than a clever one-liner that confuses readers.
|
|