0

I came across the symbol ":=" in a Python snippet. Apparently it assigns to a variable, when calling a function.

import numpy
numpy.random.shuffle( x := [1, 2, 3, 4] )
# x is now created/overwritten

Is there any documentation on this ":=" symbol?

Jos
  • 11
  • 3

1 Answers1

1

This is called the "walrus operator" and it's used for assignment expressions. It's new in Python 3.8.

This is frankly not a good use of it since all it does is save writing x again, while making the code confusing (as you noticed, lol), and incompatible with Python 3.7-. Rewrite:

import numpy
x = [1, 2, 3, 4]
numpy.random.shuffle(x)

See PEP 572 for more details and better examples, especially this one.

wjandrea
  • 28,235
  • 9
  • 60
  • 81
  • Seriously from curiosity: isn't all walrus uses are pretty much "save one line of code"? I mean, you could always write the assignment separately. Am I missing something? – Tomerikoo May 21 '20 at 14:32
  • 2
    @Tomerikoo No, there are some situations where it saves **two** lines of code! :P But seriously, check out [this example](https://www.python.org/dev/peps/pep-0572/#capturing-condition-values) from PEP 572. It's much cleaner with the walrus, especially the if-elif chain, which would otherwise have to be nested if-else's. – wjandrea May 21 '20 at 14:37
  • Oh right. User input validation is classic example of cleaner code. Nice! – Tomerikoo May 21 '20 at 14:41
  • Thanks! I can see some useful situations for this operator, but indeed, it could be confusing too :-) – Jos May 21 '20 at 14:46