Python Return Tuple From Function

Python functions can return different values, objects, and types. So Python functions can return tuples without a problem. What makes returning a tuple from a function is popular than returning the types is multiple values or objects can be returned by using a tuple.

Returning Single Value with Tuple

The tuple type can be used to return a single value even it is not so popular.

def myfun():
   name = ("name")
   return name

t = myfun()

Returning Multiple Values with Tuple

The tuple is popularly used to return multiple values from a function. We can create a tuple to return two or more values from a function. The tuple can be created at the return statement line where returned values are separated with a comma.

def myfun():
   return "ismail","baydan",35

t = myfun()

print(t)

Returning Multiple Values with Existing Tuple

Another way to return a tuple from a function is by creating a tuple variable or object before returning it with the return statement.

def myfun():
   t = ("ismail","baydan",35)
   return t

myt = myfun()

print(myt)

Assign Returned Tuple To Multiple Variables

Another powerful feature of returning a tuple from a function is the ability to assign every tuple item into a separate variable. In the following example, we will return a tuple that contains name, surname, and age information and assign this information to different variables.

def myfun():
   return "ismail","baydan",35

name,surname,age = myfun()

print(name," ",surname," ",age)

Leave a Comment