Search code examples
pythoncolon-equalspython-assignment-expression

What does colon equal (:=) in Python mean?


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

Solution

  • 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.