252

What does the := operand mean, more specifically for Python?

Can someone explain how to read this snippet of code?

node := root, cost = 0
frontier := priority queue containing node only
explored := empty set
Timur Shtatland
  • 12,024
  • 2
  • 30
  • 47
Julio
  • 2,573
  • 2
  • 11
  • 7
  • My guess is that this is pseudocode right from this wiki [article](http://en.wikipedia.org/wiki/Uniform-cost_search) and possibly the OP is asking how one interprets this code (which is an assignment) in Python – Michael Petch Sep 23 '14 at 16:37
  • Related: [What does ":=" do?](https://stackoverflow.com/questions/5344694/what-does-do). There is some history here wrt mathematical notation where single equals represents an equality test, hence the desire to disambiguate an assignment (`:=`) from an equality test (`=` or `==`). – jarmod Mar 21 '23 at 14:08
  • I found this useful reading: https://medium.com/mlearning-ai/when-and-why-to-use-over-in-python-b91168875453 – David Jun 22 '23 at 01:57

6 Answers6

293

Updated answer

In the context of the question, we are dealing with pseudocode, but starting in Python 3.8, := is actually a valid operator that allows for assignment of variables within expressions:

# Handle a matched regex
if (match := pattern.search(data)) is not None:
    # Do something with match

# A loop that can't be trivially rewritten using 2-arg iter()
while chunk := file.read(8192):
   process(chunk)

# Reuse a value that's expensive to compute
[y := f(x), y**2, y**3]

# Share a subexpression between a comprehension filter clause and its output
filtered_data = [y for x in data if (y := f(x)) is not None]

See PEP 572 for more details.

Original Answer

What you have found is pseudocode

Pseudocode is an informal high-level description of the operating principle of a computer program or other algorithm.

:= is actually the assignment operator. In Python this is simply =.

To translate this pseudocode into Python you would need to know the data structures being referenced, and a bit more of the algorithm implementation.

Some notes about psuedocode:

  • := is the assignment operator or = in Python
  • = is the equality operator or == in Python
  • There are certain styles, and your mileage may vary:

Pascal-style

procedure fizzbuzz
For i := 1 to 100 do
    set print_number to true;
    If i is divisible by 3 then
        print "Fizz";
        set print_number to false;
    If i is divisible by 5 then
        print "Buzz";
        set print_number to false;
    If print_number, print i;
    print a newline;
end

C-style

void function fizzbuzz
For (i = 1; i <= 100; i++) {
    set print_number to true;
    If i is divisible by 3
        print "Fizz";
        set print_number to false;
    If i is divisible by 5
        print "Buzz";
        set print_number to false;
    If print_number, print i;
    print a newline;
}

Note the differences in brace usage and assignment operator.

wjandrea
  • 28,235
  • 9
  • 60
  • 81
Mike McMahon
  • 7,096
  • 3
  • 30
  • 42
117

PEP572 proposed support for the := operator in Python to allow variable assignments within expressions.

This syntax is available in Python 3.8.

chadlagore
  • 1,587
  • 2
  • 12
  • 13
  • 3
    @z33k The question was asked years before the PEP was created. This certainly doesn't answer the question. Could be a comment though... – bot47 Jun 23 '19 at 13:48
  • 29
    @MaxRied I just found this answer via Google and it was exactly what I was looking for. Even if it wasn't relevant when the question was posed, it certainly is now. – Andreas T Feb 02 '20 at 17:33
  • 3
    PEP572 allows Python to have all the sort of nasty bugs that this operator allows people to have in C. – vy32 Apr 08 '20 at 14:41
  • 1
    @vy32. The more you allow a competent user to do, the more bugs you allow to be introduced by everyone. That's not a reason to restrict, in case that's what you were implying. – Mad Physicist Apr 19 '21 at 16:39
  • @MadPhysicist - I wasn't implying that this operator shouldn't be added to Python 3.8. I was merely pointing out that it would be a new source of bugs, and noting that the `=` assignment operator in C has a long and troubled history. – vy32 Apr 19 '21 at 17:25
75

This symbol := is an assignment operator in Python (mostly called as the Walrus Operator). In a nutshell, the walrus operator compresses our code to make it a little shorter.


Here's a very simple example:

# without walrus
n = 30
if n > 10:
    print(f"{n} is greater than 10")

# with walrus
if (n := 30) > 10:
    print(f"{n} is greater than 10")

These codes are the same (and outputs the same thing), but as you can see, the version with the walrus operator is compressed in just two lines of code to make things more compact.


Now, why would you use the walrus operator?

First off, don't feel obligated.

I myself even rarely use this one. I'm just using the walrus operator to compress my code a little bit, mostly when I'm working with regular expressions.

You can also find your own use case of this. What's important is you have a rough idea about it and knows when it might be helpful when you encountered a problem like this one.

And this is by far how can I explain walrus operator in a higher level. Hope you learned something.

informatik01
  • 16,038
  • 10
  • 74
  • 104
menard_codes
  • 33
  • 3
  • 8
53

The code in the question is pseudo-code; there, := represents assignment.

For future visitors, though, the following might be more relevant: the next version of Python (3.8) will gain a new operator, :=, allowing assignment expressions (details, motivating examples, and discussion can be found in PEP 572, which was provisionally accepted in late June 2018).

With this new operator, you can write things like these:

if (m := re.search(pat, s)):
    print m.span()
else if (m := re.search(pat2, s):
    …

while len(bytes := x.read()) > 0:
    … do something with `bytes`

[stripped for l in lines if len(stripped := l.strip()) > 0]

instead of these:

m = re.search(pat, s)
if m:
    print m.span()
else:
    m = re.search(pat2, s)
    if m:
        …

while True:
    bytes = x.read()
    if len(bytes) <= 0:
        return
    … do something with `bytes`

[l for l in (l.strip() for l in lines) if len(l) > 0]
Clément
  • 12,299
  • 15
  • 75
  • 115
20

Happy 3.8 Release on 14th of October!

There is new syntax := that assigns values to variables as part of a larger expression. It is affectionately known as “the walrus operator” due to its resemblance to the eyes and tusks of a walrus.

In this example, the assignment expression helps avoid calling len() twice:

if (n := len(a)) > 10:
    print(f"List is too long ({n} elements, expected <= 10)")

What’s New In Python 3.8 - Assignment expressions

wjandrea
  • 28,235
  • 9
  • 60
  • 81
Wera
  • 357
  • 2
  • 4
7

:= is also called as Walrus Operator. We can use this walrus operator to assign a value and do condition check at the same time.

Eg:

Without Walrus Operator:

a = 10
if a == 10:
   print("yes")

With Walrus Operator:

if (a := 10) == 10:
   print("Yes")

So, we can use variable a not just in statement also after that. it will simply assign new value into variable and enables condition check.

Mohideen bin Mohammed
  • 18,813
  • 10
  • 112
  • 118