To return one or more values in a function

Asked 2 years ago, Updated 2 years ago, 86 views

What kind of method do you use to return multiple values in a function? The method I'm using is as follows.

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

When there are more elements, it's harder to remember which number of elements are stored The longer the tuple, the more inefficient it is. Also, the process of unpacking the tuple is not good to see.

def g(x):
  y0 = x + 1
  y1 = x * 3
  y2 = y0 ** y3
  return {'return0':y0, 'return1':y1 ,'return2':y2 }

It is easier to understand the meaning of each element than the first method.

class ReturnValue (object): #defining the class for the value to be returned
  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 ** y3
  return ReturnValue(y0, y1, y2)
def h(x):
  result = [x + 1]
  result.append(x * 3)
  result.append(y0 ** y3)
  return result

It is similar to writing a tuple of 1. However, it is not a good idea because the elements in the list can be of different types. And in the case of tuple, the returned value cannot be changed For list, you can replace the returned value.

I usually use 2. dictionary. Which one do you prefer? I wonder if you use any other method other than the one I'm using.

python coding-style return return-value

2022-09-22 22:29

1 Answers

In Python 2.6 and later, collections.namedtuple was created for this purpose.

import collections
point = collections.namedtuple('Point', ['x', 'y'])
p = point (1, y = 2) # Can be set by parameter order or keyword
p.x, p.y # accessible by name
p[0], p[1] # Accessible by index


2022-09-22 22:29

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.