Main Content

Multiple returns from a function in Python

Archive - Originally posted on "The Horse's Mouth" - 2009-10-06 08:27:32 - Graham Ellis

Convention states that you can call a function with many parameters, but you return just one.

There's some truth in that statement, but of course you can often return a collection - an array, list, hash, dictionary or other composite object.

Here's a Python example ... 3 parameters in and 2 return values:

def foo(fee,fi,fum):
   add = fee + fi + fum
   mul = fee * fi * fum
   return add,mul
 
smaller,larger = foo(10,20,30)
 
print larger,smaller


Runs as follows:

94:3 grahamellis$ python symi
6000 60
94:3 grahamellis$


The above is a demonstration from yesterday's Python Course ... a 'live' program would include documentation and comments, and would use some more descriptive variable names too!