Return multiple values from function
Dart doesn't support multiple return values.
You can return an array,
List foo() {
return [42, "foobar"];
}
or if you want the values be typed use a Tuple
class like the package https://pub.dartlang.org/packages/tuple provides.
See also either
for a way to return a value or an error.
How can I return two values from a function in Python?
You cannot return two values, but you can return a tuple
or a list
and unpack it after the call:
def select_choice():
...
return i, card # or [i, card]
my_i, my_card = select_choice()
On line return i, card
i, card
means creating a tuple. You can also use parenthesis like return (i, card)
, but tuples are created by comma, so parens are not mandatory. But you can use parens to make your code more readable or to split the tuple over multiple lines. The same applies to line my_i, my_card = select_choice()
.
If you want to return more than two values, consider using a named tuple. It will allow the caller of the function to access fields of the returned value by name, which is more readable. You can still access items of the tuple by index. For example in Schema.loads
method Marshmallow framework returns a UnmarshalResult
which is a namedtuple
. So you can do:
data, errors = MySchema.loads(request.json())
if errors:
...
or
result = MySchema.loads(request.json())
if result.errors:
...
else:
# use `result.data`
In other cases you may return a dict
from your function:
def select_choice():
...
return {'i': i, 'card': card, 'other_field': other_field, ...}
But you might want consider to return an instance of a utility class (or a Pydantic/dataclass model instance), which wraps your data:
class ChoiceData():
def __init__(self, i, card, other_field, ...):
# you can put here some validation logic
self.i = i
self.card = card
self.other_field = other_field
...
def select_choice():
...
return ChoiceData(i, card, other_field, ...)
choice_data = select_choice()
print(choice_data.i, choice_data.card)
What's the best way to return multiple values from a function?
def f(in_str):
out_str = in_str.upper()
return True, out_str # Creates tuple automatically
succeeded, b = f("a") # Automatic tuple unpacking
Best practice for returning multiple values in Java?
No, this kind of structure doesn't exists nativily in Java, but you can look at JavaTuples library that may suit your need and provide a quite elegant solution. Using a Triplet<Boolean, String, Boolean>
how to return multiple values from a function and use that in somewhere else in python programme
functions can only return a single value.
It's easy to pack multiple values into a tuple and return that
def f(x, y):
retval1 = x + y
retval2 = x * y
return retval1, retval2
You can unpack the returned tuple like this
sumval, prodval = f(5,7)
Is it pythonic for a function to return multiple values?
Absolutely (for the example you provided).
Tuples are first class citizens in Python
There is a builtin function divmod()
that does exactly that.
q, r = divmod(x, y) # ((x - x%y)/y, x%y) Invariant: div*y + mod == x
There are other examples: zip
, enumerate
, dict.items
.
for i, e in enumerate([1, 3, 3]):
print "index=%d, element=%s" % (i, e)
# reverse keys and values in a dictionary
d = dict((v, k) for k, v in adict.items()) # or
d = dict(zip(adict.values(), adict.keys()))
BTW, parentheses are not necessary most of the time.
Citation from Python Library Reference:
Tuples may be constructed in a number of ways:
- Using a pair of parentheses to denote the empty tuple: ()
- Using a trailing comma for a singleton tuple: a, or (a,)
- Separating items with commas: a, b, c or (a, b, c)
- Using the tuple() built-in: tuple() or tuple(iterable)
Functions should serve single purpose
Therefore they should return a single object. In your case this object is a tuple. Consider tuple as an ad-hoc compound data structure. There are languages where almost every single function returns multiple values (list in Lisp).
Sometimes it is sufficient to return (x, y)
instead of Point(x, y)
.
Named tuples
With the introduction of named tuples in Python 2.6 it is preferable in many cases to return named tuples instead of plain tuples.
>>> import collections
>>> Point = collections.namedtuple('Point', 'x y')
>>> x, y = Point(0, 1)
>>> p = Point(x, y)
>>> x, y, p
(0, 1, Point(x=0, y=1))
>>> p.x, p.y, p[0], p[1]
(0, 1, 0, 1)
>>> for i in p:
... print(i)
...
0
1
Returning multiple values from a C++ function
For returning two values I use a std::pair
(usually typedef'd). You should look at boost::tuple
(in C++11 and newer, there's std::tuple
) for more than two return results.
With introduction of structured binding in C++ 17, returning std::tuple
should probably become accepted standard.
Related Topics
Dealing with the Class Imbalance in Binary Classification
Numpy/Scipy Equivalent of R Ecdf(X)(X) Function
Sqlalchemy: Print the Actual Query
How to Compile Opencv for iOS7 (Arm64)
Python Code to Remove HTML Tags from a String
Plotting 3-Tuple Data Points in a Surface/Contour Plot Using Matplotlib
Why Is Variable1 += Variable2 Much Faster Than Variable1 = Variable1 + Variable2
What Is a "Good" Palette for Divergent Colors in R? (Or: Can Viridis and Magma Be Combined Together)
Beautifulsoup Not Grabbing Dynamic Content
Calling Custom Functions from Python Using Rpy2
How to Change the Styles of Pandas Dataframe Headers
How to Set the R_Home Environment Variable to the R Home Directory
How to Use Tailwindcss with Django
Error When Installing Rpy2 Module in Python with Easy_Install
Download Returned Zip File from Url
Authentication Plugin 'Caching_Sha2_Password' Is Not Supported
Python Pandas: Get Index of Rows Which Column Matches Certain Value