Walrus Operator
The walrus operator, :=
, is a new feature introduced in Python 3.8 and it allows you to assign values to variables within an expression. The operator works by using the same syntax as the assignment operator, =
, but it appears on the left-hand side of an expression.
Here are a few code examples to show you how to use the walrus operator.
Example 1
## Finding the first even number in a list using the walrus operator
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
for num in numbers:
if (even := num % 2 == 0):
print(f"The first even number is: {even}")
break
## Output:
## The first even number is: True
This example demonstrates how to use the walrus operator to find the first even number in a list. The list numbers
contains integers from 1 to 10. In the for
loop, we iterate through the numbers
list and use the walrus operator :=
to assign the result of the expression num % 2 == 0
to the variable even
. If even
is True
, it means that num
is an even number. In this case, the if
statement is satisfied and the first even number is printed along with a message. The break
statement is used to stop the loop when the first even number is found.
Example 2
## Using the walrus operator in a while loop
counter = 0
while (counter := counter + 1) <= 10:
print(counter)
## Output:
## 1
## 2
## âĶâĶ
## 10
In this example, we use the walrus operator in a while
loop. The variable counter
is initialized to 0 and the while
loop continues to run as long as counter
is less than or equal to 10. In each iteration of the loop, the walrus operator is used to update the value of counter
by incrementing it by 1. The updated value of counter
is then used in the next iteration of the loop. The loop prints the value of counter
in each iteration, resulting in the numbers 1 to 10 being printed.
Example 3
## Using the walrus operator in a list comprehension
squared_numbers = [num * num for num in range(10) if (even := num % 2 == 0)]
print(squared_numbers)
## Output:
## [0, 4, 16, 36, 64]
In this example, we use the walrus operator in a list comprehension. The list comprehension is used to create a list of the squares of the even numbers from 0 to 9. The list comprehension consists of two parts: an expression num * num
and a conditional clause if (even := num % 2 == 0)
. The expression num * num
calculates the square of the current number in the loop num
. The conditional clause uses the walrus operator to assign the result of the expression num % 2 == 0
to the variable even
. If even
is True
, it means that num
is an even number, and its square is included in the list squared_numbers
. The list comprehension generates the list [0, 4, 16, 36, 64]
.
It's important to note that the walrus operator is intended for use in specific cases where you need to assign a value within an expression and use that same value multiple times. It is not meant to replace traditional assignment statements, and it's recommended to use it sparingly to improve code readability.