Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assignment to None

Tags:

python

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.

like image 736
Joel Avatar asked Mar 26 '10 11:03

Joel


People also ask

What does := mean in Python?

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?

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.

What does assignment mean in Python?

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.


2 Answers

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.

like image 146
SilentGhost Avatar answered Oct 22 '22 03:10

SilentGhost


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.

like image 9
Nikwin Avatar answered Oct 22 '22 04:10

Nikwin