45

How to return more than one variable from a function in Python?

Eugene Yarmash
  • 142,882
  • 41
  • 325
  • 378
user46646
  • 153,461
  • 44
  • 78
  • 84

3 Answers3

158

You separate the values you want to return by commas:

def get_name():
   # you code
   return first_name, last_name

The commas indicate it's a tuple, so you could wrap your values by parentheses:

return (first_name, last_name)

Then when you call the function you a) save all values to one variable as a tuple, or b) separate your variable names by commas

name = get_name() # this is a tuple
first_name, last_name = get_name()
(first_name, last_name) = get_name() # You can put parentheses, but I find it ugly
Cristian
  • 42,563
  • 25
  • 88
  • 99
  • 3
    Your answer is much more clear, more concise, and easier to understand than several answers I have seen for similar questions. Thank you. – culix Jul 03 '12 at 04:47
14

Here is also the code to handle the result:

def foo (a):
    x=a
    y=a*2
    return (x,y)

(x,y) = foo(50)
Staale
  • 27,254
  • 23
  • 66
  • 85
6

Return as a tuple, e.g.

def foo (a):
    x=a
    y=a*2
    return (x,y)
ConcernedOfTunbridgeWells
  • 64,444
  • 15
  • 143
  • 197