How does Python return multiple values from a function?
<p>I have written the following code:</p>

<pre><code>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]

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

f = FigureOut()
f.setName("Allen Solly")
name = f.getName()
print (name)
</code></pre>

<p>I get the following <strong>Output:</strong></p>

<pre><code>('Allen', 'Solly')
</code></pre>

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

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

<p>Python will return a <code>tuple</code> in this case since the return specifies <em>comma separated values</em>. Multiple values can only be returned inside containers.</p>

<p>You can look at the byte code generated from a function returning values like yours by using <a href="https://docs.python.org/3/library/dis.html#dis.dis" rel="nofollow"><code>dis.dis</code></a>. For comma separated values, it looks like:</p>

<pre><code>def foo(a, b):
    return a,b    

import dis    
dis.dis(foo)
  2           0 LOAD_FAST                0 (a)
              3 LOAD_FAST                1 (b)
              6 BUILD_TUPLE              2
              9 RETURN_VALUE
</code></pre>

<p>As you can see the values are first loaded on the stack and then a <a href="https://docs.python.org/3/library/dis.html#opcode-BUILD_TUPLE" rel="nofollow"><code>BUILD_TUPLE</code></a> (grabbing the previous <code>2</code> elements placed on the stack) is generated. Python knows to create tuple due to thhe commas being present.</p>

<p>You could alternatively specify another return type, for example a list, for this case a <a href="https://docs.python.org/3/library/dis.html#opcode-BUILD_LIST" rel="nofollow"><code>BUILD_LIST</code></a> is going to be issued following the same semantics as it's tuple equivalent:</p>

<pre><code>def foo(a, b):
    return [a, b]

import dis
dis.dis(foo)
  2           0 LOAD_FAST                0 (a)
              3 LOAD_FAST                1 (b)
              6 BUILD_LIST               2
              9 RETURN_VALUE
</code></pre>

<p>To summarize, <em>one actual object is returned</em>, if that object is of a container type, it in essence can contain multiple values giving the impression of multiple results.</p>

python function python-3.x return