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

sectrean picture sectrean · Sep 2, 2008 · Viewed 76.2k times · Source

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?

Answer

John Millikin picture John Millikin · Sep 2, 2008
def f(in_str):
    out_str = in_str.upper()
    return True, out_str # Creates tuple automatically

succeeded, b = f("a") # Automatic tuple unpacking