I have a function which returns 3 numbers, e.g.:
def numbers():
return 1,2,3
usually I call this function to receive all three returned numbers e.g.:
a, b, c = numbers()
However, I have one case in which I only need the first returned number. I tried using:
a, None, None = numbers()
But I receive "SyntaxError: assignment to None".
I know, of course, that I can use the first option I mentioned and then simply not use the "b" and "c" variables. However, this seems like a "waste" of two vars and feels like wrong programming.
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.
Can a Python set contain None? None is not the same as 0, False, or an empty string. None is a data type of its own (NoneType) and only None can be None.
An assignment statement evaluates the expression list (remember that this can be a single expression or a comma-separated list, the latter yielding a tuple) and assigns the single resulting object to each of the target lists, from left to right.
a, _, _ = numbers()
is a pythonic way to do this. In Python 3, you could also use:
a, *_ = numbers()
To clarify _
is a normal variable name in Python, except it is conventionally used to refer to non-important variables.
Another way is of course a=numbers()[0]
, if you do not want to declare another variable. Having said this though, I generally use _ myself.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With