top of page

Returning multiple values from a function in Python

Assume we have a method which takes in full name and returns first & last names seperately.

def split_fullname(fullname):
    firstname = fullname.split()[0]
    lastname = fullname.split()[-1]
    return firstname, lastname  

we can return multiple values from a function by separating them with a comma

first_name, last_name = split_fullname('Bruce Wayne')
# Since we return 2 values, we need 2 variables to store them.
print(f'First Name: {first_name}, Last Name: {last_name}')

Note: We are not really returning multiple values here. We're just returning a tuple object of two elements. It is later unpacked when we provide two variables to store them. If we give only one variable, it will be stored as a tuple object. So whenever we return multiple values from a function, it will be returned as a single tuple which we can unpack later on.

#functions #python

bottom of page