Question 17: Understanding the Walrus Operator

The Walrus Operator, introduced in Python 3.8, allows you to assign a value to a variable as part of an expression.

This operator, :=, is useful for simplifying code and reducing redundancy by combining variable assignment and expression evaluation.

Question: Walrus Operator

Which of the following options correctly uses the Walrus Operator to simplify the code and output the expected result?

# Given a list of numbers, find the first number greater than 10.
numbers = [2, 5, 8, 12, 18, 1]

for num in numbers:
    if num > 10:
        print(num)
        break

Option A:

# Option A
numbers = [2, 5, 8, 12, 18, 1]

for num in numbers:
    if (found := num) > 10:
        print(found)
        break

Option B:

# Option B
numbers = [2, 5, 8, 12, 18, 1]

if num > 10:
    print(num := num)
    break

Option C:

# Option C
numbers = [2, 5, 8, 12, 18, 1]

if (num := numbers[3]) > 10:
    print(num)

Option D:

# Option D
numbers = [2, 5, 8, 12, 18, 1]

for num in numbers:
    print(num := num > 10)















Answer: A

  • Option A: Correctly uses the Walrus Operator to simplify the code. The condition checks if num is greater than 10, and if so, assigns it to found and prints it.
  • Option B: Incorrect because it uses the Walrus Operator outside the loop, which doesn’t correctly check each element.
  • Option C: Incorrect because it only checks the fourth element in the list and doesn’t iterate over all elements.
  • Option D: Incorrect because it mistakenly uses the Walrus Operator to compare and assign True or False to num instead of the number itself.

Leave a Reply