Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'No write' variable in Python

Tags:

python

matlab

In MATLAB you have the ability to return tuples and assign to tuples of values the same as you do so in Python. In MATLAB, if a function returns a value you don't want to assign to anything, you assign it to the special variable ~. For example, say a function f() returns a tuple (1, 2), then:

~, b = f()

Assigns 2 to b and 1 to nothing.

Is there an equivalent to this in Python? I understand I could just do:

a, b = f()

and ignore the value of a but I'd prefer skipping the assignment to a altogether. Rewriting the function f() is not an option.

I apologize if my Python terminology is wrong.

like image 609
Sadly Not Avatar asked May 19 '26 23:05

Sadly Not


2 Answers

A common idiom in Python is to use _ for this purpose.

However it's not necessarily a good idea because this variable is also used in the interactive interpreter for the last result and assigning to it will stop this useful feature from working.

Also _ is sometimes used for string translation, e.g. with gettext.

like image 192
Mark Byers Avatar answered May 21 '26 11:05

Mark Byers


Alternatively you can always just return the part of the tuple, you are interested in:

b = f()[1]
like image 31
miku Avatar answered May 21 '26 13:05

miku



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!