Returning Multiple Values In Python

In Python function can return multiple values. There are different ways to return multiple values like using objects, tuples, lists, dictionaries, and data classes. In this tutorial, we examine how to return multiple values using these different methods. Multiple values can be variables, objects, lists, etc.

Return Multiple Values Using Tuple

Python provides the Tuple data type which is an immutable object that contains single or more items. The easiest and most popular way to return multiple values from a function is using the tuple type and putting all values into a single tuple. Tuple can be defined by separating values or items with a comma.

def myfun():
   return 1,2,"ahmet"

mytuple = myfun()

Alternatively, we can set all returned values into separate variables. In the following example, we store returned values in variables one, two, and name.

def myfun():
   return 1,2,"ahmet"

one,two,name = myfun()

Return Multiple Values Using Object

Object type is used to store single or more data according to the specified class definition. An object can be used to return multiple values from a function. All values will be stored inside a function.

class Person:
   def __init__(self):
      self.name="ismail"
      self.surname="baydan"

def CreatePerson():
   return Person()

p = CreatePerson()

print(p.name," ",p.surname)

Return Multiple Values Using List

Python list is used to store multiple items in a single variable. The list is similar to the array and we can use the list order to return multiple values or items.

def myfun():
   return [1,2,"ahmet"]

mylist = myfun()

print(mylist[0])

print(mylist[1])

print(mylist[2])

Return Multiple Values Using Dictionary

Python dictionary is another type that can be used to return multiple values from functions. Dictionary type stores items as “key:value” pair and every value should be specified with a key.

def myfun():
   return {"name":"ahmet","surname":"baydan","age":8}

mydict = myfun()

print(mydict["name"])

print(mydict["surname"])

print(mydict["age"])

Leave a Comment