Blue Moon
Blue Moon

Reputation: 4651

How to get a single output from a function with multiple outputs?

I have the following simple function:

def divide(x, y):
    quotient = x/y
    remainder = x % y
    return quotient, remainder  

x = divide(22, 7)

If I accesss the variable x I get:

x
Out[139]: (3, 1)

Is there a way to get only the quotient or the remainder?

Upvotes: 3

Views: 10706

Answers (3)

jonrsharpe
jonrsharpe

Reputation: 122023

You have two broad options, either:

  1. Modify the function to return either or both as appropriate, for example:

    def divide(x, y, output=(True, True)):
        quot, rem = x // y, x % y
        if all(output):
            return quot, rem
        elif output[0]:
            return quot
        return rem
    
    quot = divide(x, y, (True, False))
    
  2. Leave the function as it is, but explicitly ignore one or the other of the returned values:

    quot, _ = divide(x, y)  # assign one to _, which means ignore by convention
    rem = divide(x, y)[1]  # select one by index
    

I would strongly recommend one of the latter formulations; it's much simpler!

Upvotes: 2

SillyWilly
SillyWilly

Reputation: 388

You can either unpack the return values when you call your method:

x, y = divide(22, 7)

Or you can just grab the first returned value:

x = divide(22, 7)[0]

Upvotes: 2

Dor-Ron
Dor-Ron

Reputation: 1807

You are essentially returning a tuple, which is an iterable we can index, so in the example above:

print x[0] would return the quotient and

print x[1] would return the remainder

Upvotes: 5

Related Questions