You can use x = func()[0] to return the first value, x = func()[1] to return the second, and so on.
If you want to get multiple values at a time, use something like x, y = func()[2:4].
You can use x = func()[0] to return the first value, x = func()[1] to return the second, and so on.
If you want to get multiple values at a time, use something like x, y = func()[2:4].
One common convention is to use a "_" as a variable name for the elements of the tuple you wish to ignore. For instance:
def f():
return 1, 2, 3
_, _, x = f()
You can use star unpacking to gather all additional return values into a list:
x, *y = fun()
x will contain the first return value. y will be a list of the remaining values. y will be empty if there is only one return value. This particular example will only work if the function returns a tuple, even if there is only one value.
When fun always returns 1 or 2 values, you can just do
if y:
print(y[0])
else:
print('only one value')
If, on the other hand, you want to completely ignore the number of return values, do
*x = fun()
Now all the arguments will be gathered into the list. You can then print it with either
print(x)
or
print(*x)
The latter will pass each element as a separate argument, exactly as if you did
x, y, z = fun()
print(x, y, z)
The reason to use *x = fun() instead of just x = fun() is to get an error immediately when a function returns something that isn't a tuple. Think of it as an assertion to remind you to write fun properly.
Since this form of star unpacking only works in Python 3, your only option in Python 2 is to do
x = fun()
and to inspect the result manually.
There are several ways to get multiple return values.
Example 1:
def test_fun():
return 1,2
def test_call():
x, y = test_fun()
print x
print y
you will get correct output:
1
2
When you would like to ignore several return values, you can use * before a variable in python3.
Example 2:
def test_fun2():
return 1,2,3
def test_call2():
x, *y = test_fun2()
print x
print y
you will get the result:
1
(2, 3)
Push them onto the stack
This really only applies to stack-based languages, and perhaps Assembly. The good thing about this approach is that its somewhat more natural to work with the returned values. If you do divmod, you can pop once to get the quotient, pop the next element to get the remainder. The downside is that if you want to call a function that returns multiple values and immediately pass them on, it might be a bit cumbersome, depending on the language.
Custom types
In languages such as Java and Kotlin, which really love their nominal typing, you would make a new class specific to that one function. For example, divmod might return a DivmodResult object with fields quotient and remainder (Kotlin does have a Pair class in its standard library, but it's dropped actual tuples now).
Advantages:
- When you have to return 4 or more values, it really helps to have a class specifically for that purpose if you have a statically typed language. I'd rather see a return type of
FooResultthan some enormous tuple like(int, String, BarProducer, String, int)
Disadvantages:
- Making a whole class for a single function is annoying. Some languages do have syntactic sugar for this (e.g.
data classin Kotlin) but it's so much easier to use something like tuples or lists instead. In Java, you'll have to make getters and setters and constructors for a minor class that might only be used in one or two places.
Using the underscore for unused variables is definitely acceptable. Be warned though, in some codebases it's not an option as that identifier is reserved as shorthand for gettext. This is the most frequent objection to this style (though it's not an issue for the majority as far as I can judge). I'd still recommend it, and always use it myself.
Names like dummy or unused tend to irritate me personally, and I don't see them terribly often (in Python, that is - I know a Delphi codebase which uses dummy liberally, and it has also leaked into scripts associated with the program in question). I'd advice you against it.
Just extracting one item from the returned tuple is okay too. It also saves some hassle with getting the number of unused values right. Note though that it's has two potential downsides:
- It doesn't blow up if the number of values is different from what you expect. This may be useful to detect mixups and typos.
- It only works when the return value is a sequence (that's mostly tuples and lists, but let's stay general). Offhand, I know one class in my code (a 2D vector) that is iterable and yields a constant number of values (and thus can be used in unpacking assignments), but is not indexable.
Pylint has gotten me in the habit of doing it this way:
widget, _parent, _children = f()
That is, unused results have a descriptive name prefixed by _. Pylint regards locals prefixed with _ as unused, and globals or attributes prefixed with _ as private.
Hello developers, I want to know about how can I return multiple values from a function. I have read few articles but still confused.
Named tuples were added in 2.6 for this purpose. Also see os.stat for a similar builtin example.
>>> import collections
>>> Point = collections.namedtuple('Point', ['x', 'y'])
>>> p = Point(1, y=2)
>>> p.x, p.y
1 2
>>> p[0], p[1]
1 2
In recent versions of Python 3 (3.6+, I think), the new typing library got the NamedTuple class to make named tuples easier to create and more powerful. Inheriting from typing.NamedTuple lets you use docstrings, default values, and type annotations.
Example (From the docs):
class Employee(NamedTuple): # inherit from typing.NamedTuple
name: str
id: int = 3 # default value
employee = Employee('Guido')
assert employee.id == 3
For small projects I find it easiest to work with tuples. When that gets too hard to manage (and not before) I start grouping things into logical structures, however I think your suggested use of dictionaries and ReturnValue objects is wrong (or too simplistic).
Returning a dictionary with keys "y0", "y1", "y2", etc. doesn't offer any advantage over tuples. Returning a ReturnValue instance with properties .y0, .y1, .y2, etc. doesn't offer any advantage over tuples either. You need to start naming things if you want to get anywhere, and you can do that using tuples anyway:
def get_image_data(filename):
[snip]
return size, (format, version, compression), (width,height)
size, type, dimensions = get_image_data(x)
IMHO, the only good technique beyond tuples is to return real objects with proper methods and properties, like you get from re.match() or open(file).