Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the best way to return multiple values from a function?

I have a function where I need to do something to a string. I need the function to return a boolean indicating whether or not the operation succeeded, and I also need to return the modified string.

In C#, I would use an out parameter for the string, but there is no equivalent in Python. I'm still very new to Python and the only thing I can think of is to return a tuple with the boolean and modified string.

Related question: Is it pythonic for a function to return multiple values?

like image 718
John Rutherford Avatar asked Sep 01 '08 22:09

John Rutherford


People also ask

Can I return multiple values from a function in Python?

Python functions can return multiple values. These values can be stored in variables directly. A function is not restricted to return a variable, it can return zero, one, two or more values.

How do I return many values?

You can return multiple values by bundling those values into a dictionary, tuple, or a list. These data types let you store multiple similar values. You can extract individual values from them in your main program. Or, you can pass multiple values and separate them with commas.

How do you return multiple numbers in Python?

In Python, you can return multiple values by simply return them separated by commas. In Python, comma-separated values are considered tuples without parentheses, except where required by syntax. For this reason, the function in the above example returns a tuple with each value as an element.

Can value returning functions return multiple values?

In C or C++, we cannot return multiple values from a function directly.


1 Answers

def f(in_str):     out_str = in_str.upper()     return True, out_str # Creates tuple automatically  succeeded, b = f("a") # Automatic tuple unpacking 
like image 101
John Millikin Avatar answered Sep 22 '22 11:09

John Millikin