Sadly Not
Sadly Not

Reputation: 234

'No write' variable in Python

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.

Upvotes: 2

Views: 307

Answers (2)

Mark Byers
Mark Byers

Reputation: 838266

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.

Upvotes: 13

miku
miku

Reputation: 188034

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

b = f()[1]

Upvotes: 10

Related Questions