How does Python return multiple values from a function?

107,051

Solution 1

Since the return statement in getName specifies multiple elements:

def getName(self):
   return self.first_name, self.last_name

Python will return a container object that basically contains them.

In this case, returning a comma separated set of elements creates a tuple. Multiple values can only be returned inside containers.

Let's use a simpler function that returns multiple values:

def foo(a, b):
    return a, b

You can look at the byte code generated by using dis.dis, a disassembler for Python bytecode. For comma separated values w/o any brackets, it looks like this:

>>> import dis
>>> def foo(a, b):
...     return a,b        
>>> dis.dis(foo)
  2           0 LOAD_FAST                0 (a)
              3 LOAD_FAST                1 (b)
              6 BUILD_TUPLE              2
              9 RETURN_VALUE

As you can see the values are first loaded on the internal stack with LOAD_FAST and then a BUILD_TUPLE (grabbing the previous 2 elements placed on the stack) is generated. Python knows to create a tuple due to the commas being present.

You could alternatively specify another return type, for example a list, by using []. For this case, a BUILD_LIST is going to be issued following the same semantics as it's tuple equivalent:

>>> def foo_list(a, b):
...     return [a, b]
>>> dis.dis(foo_list)
  2           0 LOAD_FAST                0 (a)
              3 LOAD_FAST                1 (b)
              6 BUILD_LIST               2
              9 RETURN_VALUE

The type of object returned really depends on the presence of brackets (for tuples () can be omitted if there's at least one comma). [] creates lists and {} sets. Dictionaries need key:val pairs.

To summarize, one actual object is returned. If that object is of a container type, it can contain multiple values giving the impression of multiple results returned. The usual method then is to unpack them directly:

>>> first_name, last_name = f.getName()
>>> print (first_name, last_name)

As an aside to all this, your Java ways are leaking into Python :-)

Don't use getters when writing classes in Python, use properties. Properties are the idiomatic way to manage attributes, for more on these, see a nice answer here.

Solution 2

From Python Cookbook v.30

def myfun():
    return 1, 2, 3

a, b, c = myfun()

Although it looks like myfun() returns multiple values, a tuple is actually being created. It looks a bit peculiar, but it’s actually the comma that forms a tuple, not the parentheses

So yes, what's going on in Python is an internal transformation from multiple comma separated values to a tuple and vice-versa.

Though there's no equivalent in you can easily create this behaviour using array's or some Collections like Lists:

private static int[] sumAndRest(int x, int y) {
    int[] toReturn = new int[2];

    toReturn[0] = x + y;
    toReturn[1] = x - y;

    return toReturn;

}

Executed in this way:

public static void main(String[] args) {
    int[] results = sumAndRest(10, 5);

    int sum  = results[0];
    int rest = results[1];

    System.out.println("sum = " + sum + "\nrest = " + rest);

}

result:

sum = 15
rest = 5

Solution 3

Here It is actually returning tuple.

If you execute this code in Python 3:

def get():
    a = 3
    b = 5
    return a,b
number = get()
print(type(number))
print(number)

Output :

<class 'tuple'>
(3, 5)

But if you change the code line return [a,b] instead of return a,b and execute :

def get():
    a = 3
    b = 5
    return [a,b]
number = get()
print(type(number))
print(number)

Output :

<class 'list'>
[3, 5]

It is only returning single object which contains multiple values.

There is another alternative to return statement for returning multiple values, use yield( to check in details see this What does the "yield" keyword do in Python?)

Sample Example :

def get():
    for i in range(5):
        yield i
number = get()
print(type(number))
print(number)
for i in number:
    print(i)

Output :

<class 'generator'>
<generator object get at 0x7fbe5a1698b8>
0
1
2
3
4

Solution 4

Python functions always return a unique value. The comma operator is the constructor of tuples so self.first_name, self.last_name evaluates to a tuple and that tuple is the actual value the function is returning.

Solution 5

Whenever multiple values are returned from a function in python, does it always convert the multiple values to a list of multiple values and then returns it from the function??

I'm just adding a name and print the result that returns from the function. the type of result is 'tuple'.

  class FigureOut:
   first_name = None
   last_name = None
   def setName(self, name):
      fullname = name.split()
      self.first_name = fullname[0]
      self.last_name = fullname[1]
      self.special_name = fullname[2]
   def getName(self):
      return self.first_name, self.last_name, self.special_name

f = FigureOut()
f.setName("Allen Solly Jun")
name = f.getName()
print type(name)


I don't know whether you have heard about 'first class function'. Python is the language that has 'first class function'

I hope my answer could help you. Happy coding.

Share:
107,051

Related videos on Youtube

User_Targaryen
Author by

User_Targaryen

"I will not go down without a fight!!"

Updated on June 06, 2020

Comments

  • User_Targaryen
    User_Targaryen almost 4 years

    I have written the following code:

    class FigureOut:
       def setName(self, name):
          fullname = name.split()
          self.first_name = fullname[0]
          self.last_name = fullname[1]
    
       def getName(self):
          return self.first_name, self.last_name
    
    f = FigureOut()
    f.setName("Allen Solly")
    name = f.getName()
    print (name)
    

    I get the following Output:

    ('Allen', 'Solly')
    

    Whenever multiple values are returned from a function in python, does it always convert the multiple values to a list of multiple values and then returns it from the function?

    Is the whole process same as converting the multiple values to a list explicitly and then returning the list, for example in JAVA, as one can return only one object from a function in JAVA?

    • khelwood
      khelwood over 7 years
      If you return two items from a function, then you are returning a tuple of length two, because that is how returning multiple items works. It's not a list.
    • User_Targaryen
      User_Targaryen over 7 years
      @khelwood: So, is it a special feature in python?? One which is not present in languages like JAVA, C++ ..??
    • khelwood
      khelwood over 7 years
      It is a feature not present in languages that do not support returning multiple values.
    • User_Targaryen
      User_Targaryen over 7 years
      @khelwood: So, actually it does not return multiple values but a tuple of multiple values. Am I right??
    • khelwood
      khelwood over 7 years
      I would say that tuples are the mechanism by which Python allows you to return multiple values.
  • Coder Guy
    Coder Guy over 5 years
    Moreover, getThis and setThat are obsolete hold-overs from the Java bean days. I would like to see an end to this paradigm once and for all. object.foo() implies a "get" and object.foo(value) already implies a set.