Say I have a Python function that returns multiple values in a tuple:
def func():
return 1, 2
Is there a nice way to ignore one of the results rather than just assigning to a temporary variable? Say if I was only interested in the first value, is there a better way than this:
x, temp = func()
Remember, when you return more than one item, you're really returning a tuple. So you can do things like this:
The best solution probably is to name things instead of returning meaningless tuples. Unless there is some logic behind the order of the returned items.
You could even use namedtuple if you want to add extra information about what you are returning:
If the things you return are often together then it may be a good idea to even define a class for it.
This seems like the best choice to me:
It's not cryptic or ugly (like the func()[index] method), and clearly states your purpose.
One common convention is to use a "_" as a variable name for the elements of the tuple you wish to ignore. For instance:
This is not a direct answer to the question. Rather it answers this question: "How do I choose a specific function output from many possible options?".
If you are able to write the function (ie, it is not in a library you cannot modify), then add an input argument that indicates what you want out of the function. Make it a named argument with a default value so in the "common case" you don't even have to specify it.
This method gives the function "advanced warning" regarding the desired output. Consequently it can skip unneeded processing and only do the work necessary to get your desired output. Also because Python does dynamic typing, the return type can change. Notice how the example returns a scalar, a list or a tuple... whatever you like!
When you have many output from a function and you don't want to call it multiple times, I think the clearest way for selecting the results would be :
As a minimum working example, also demonstrating that the function is called only once :
And the values are as expected :
For convenience, Python list indexes can also be used :
Returns : a = 3 and b = 12