How do we return multiple values in Python?

PythonServer Side ProgrammingProgramming

It is possible to return multiple values from a function in the form of tuple, list, dictionary or an object of a user defined class

Return as tuple

>>> def function():
      a=10; b=10
      return a,b

>>> x=function()
>>> type(x)
<class 'tuple'>
>>> x
(10, 10)
>>> x,y=function()
>>> x,y
(10, 10)

Return as list

>>> def function():
      a=10; b=10
      return [a,b]

>>> x=function()
>>> x
[10, 10]
>>> type(x)
<class 'list'>

Return as dictionary

>>> def function():
      d=dict()
      a=10; b=10
      d['a']=a; d['b']=b
      return d

>>> x=function()
>>> x
{'a': 10, 'b': 10}
>>> type(x)
<class 'dict'>

Return as object of user defined class

>>> class tmp:
def __init__(self, a,b):
self.a=a
self.b=b


>>> def function():
      a=10; b=10
      t=tmp(a,b)
      return t

>>> x=function()
>>> type(x)
<class '__main__.tmp'>
>>> x.a
10
>>> x.b
10
raja
Published on 06-Feb-2018 07:17:45
Advertisements