Skip to content

Instantly share code, notes, and snippets.

@rodigu
Last active March 25, 2025 15:30
Show Gist options
  • Save rodigu/af04dc1885e3231e710f6752701ea5a2 to your computer and use it in GitHub Desktop.
Save rodigu/af04dc1885e3231e710f6752701ea5a2 to your computer and use it in GitHub Desktop.
code golfing with the the assignment expression operator (the golfing walrus `:=`)

the walrus operator, introduced in python 3.8, has been quite an useful tool.

it's documentation gives some examples of its intended use:

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

before the introduction of the walrus, you'd have to do:

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

which is evidently dreadfully inneficient and expensive to implement

today i was wondering if i could use the walrus within other python expressions that aren't conditional statements

the answer was yes, of course. meaning you can do some beautiful mid-assignment assignments:

a=(b:=3)+2

the full potential of this finding is yet to be properly examined

however, i do get the vague sense that this could be potentially quite useful with code-golfing

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment