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

后端 未结 5 1858
-上瘾入骨i
-上瘾入骨i 2020-12-05 12:59

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

Can someone explain how to read this snippet of code?

node := root, cost =          


        
5条回答
  •  不知归路
    2020-12-05 13:16

    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

提交回复
热议问题