Python function return multiple values

In Python, a function can return multiple values by simply separating them with commas in the return statement. Here’s an example:

def get_data():
    name = "John"
    age = 30
    city = "New York"
    return name, age, city

# Calling the function and unpacking the returned values
person_name, person_age, person_city = get_data()

print("Name:", person_name)
print("Age:", person_age)
print("City:", person_city)

Here, the get_data() function returns three values: name, age, and city. When the function is called and its return value is assigned to three variables (person_name, person_age, person_city), Python automatically unpacks the returned tuple into these variables.

In Python, a function can return multiple values by packing them into a tuple, list, or dictionary. Here are a few examples:

Returning a Tuple:

def multiple_values():
    # Some computations
    a = 10
    b = 20
    c = 30
    return a, b, c

result = multiple_values()
print(result)  # Output: (10, 20, 30)

Returning a List:

def multiple_values():
    # Some computations
    a = 10
    b = 20
    c = 30
    return [a, b, c]

result = multiple_values()
print(result)  # Output: [10, 20, 30]

Returning a Dictionary:

def multiple_values():
    # Some computations
    a = 10
    b = 20
    c = 30
    return {'a': a, 'b': b, 'c': c}

result = multiple_values()
print(result)  # Output: {'a': 10, 'b': 20, 'c': 30}

You can then unpack these values when calling the function:

a, b, c = multiple_values()
print(a, b, c)  # Output: 10 20 30

This allows you to effectively return multiple values from a function in Python.

About the author

Business Dev | Tech Lead | Outsourcing Manager Having a 10 Years of experience in IT Development & Marketing

Leave a Reply