Returning Multiple Values in Python?

PythonServer Side ProgrammingProgramming

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.

This is the default property of python to return multiple values/variables which is not available in many other programming languages like C++ or Java.

For returning multiple values from a function, we can return tuple, list or dictionary object as per our requirement.

Method 1: Using tuple

def func(x):
   y0 = x+ 1
   y1 = x * 3
   y2 = y0 ** 3
   return (y0, y1, y2)

However, above program get problematic as the number of values returned increases. In case if we want to return six or seven values? Sure, we can keep tupling them, but it gets easy to forget which value is where. Also its gets little messy to unpack them wherever we want to receive them.

Method 2: Using a dictionary

Another better solution is to use dictionary.

def func(x):
   y0 = x+ 1
   y1 = x * 3
   y2 = y0 ** 3
   return {'y0': y0, 'y1': y1, 'y2': y2}

Now, we have a mechanism whereby we can project out a particular member of the returned object.

For example −

result[‘y1’]

Method 3: Using a class

Another option is to use class, where we could return a specialized structure.

class ReturnValue(obj):
   def __init__(self, y0, y1, y2):
      self.y0 = y0
      self.y1 = y1
      self.y2 = y2

def g(x):
   y0 = x + 1
   y1 = x * 3
   y2 = y0 ** 3
   return ReturnValue (y0, y1, y2)

Method 4: Using a list

Another method is using a list.

def func(x):
   result = [x + 1]
   result.append(x * 3)
   result.append(y0 ** 3)
   return result

Method 5: Using generator

We can opt this option of using the yield to return multiple values one by one, in case we have to return a hunge number of values then using sequences may consume lots of system resources.

def func(x):
   y0 = x + 1
   yield y0
   yield x * 3
   yield y0 ** 3

Which method is best to return multiple values from a function?

It all depends on your taste or requirement, which method you like more. You could choose the – dictionary route as it involves less set-up work. Or you could opt – class route as that may help you avoid confusing what a dictionary represents. Or you could choose generator to yield values one by one.

raja
Published on 02-May-2019 12:23:04
Advertisements