Altcademy - a Forbes magazine logo Best Coding Bootcamp 2023

How to return multiple values in Python

Introduction

Python is a versatile and powerful programming language that can be used to accomplish a variety of tasks. One common task in programming is returning multiple values from a function. In this blog post, we will explore different ways to return multiple values in Python, along with code examples, intuitions, and analogies to help you understand the concepts better.

Basic Functions in Python

Before we dive into returning multiple values, let's first understand the basics of functions in Python. A function is a reusable piece of code that performs a specific task. Functions help to keep your code organized, make it more readable, and allow you to reuse code in different parts of your program.

Here's a simple example of a function that adds two numbers and returns the result:

def add_numbers(a, b):
    result = a + b
    return result

sum = add_numbers(3, 5)
print(sum)  # Output: 8

In this example, we define a function called add_numbers that takes two arguments, a and b, and returns the sum of these two numbers. We then call the function with the arguments 3 and 5, and store the result in a variable called sum. Finally, we print the value of sum, which is 8.

Now that we have a basic understanding of functions in Python, let's explore different ways to return multiple values.

Returning Multiple Values Using Tuples

In Python, a tuple is a collection of ordered, immutable elements, enclosed in round brackets (or parentheses). Tuples are similar to lists, but unlike lists, they cannot be modified once created. This means that you can't add, remove, or change elements in a tuple.

To return multiple values from a function, you can simply return a tuple containing all the values. Here's an example that demonstrates how to return multiple values using tuples:

def get_name_and_age():
    return ("Alice", 30)

name, age = get_name_and_age()
print(name)  # Output: Alice
print(age)   # Output: 30

In this example, we define a function called get_name_and_age that returns a tuple containing two values: a string "Alice" and an integer 30. When we call this function, we can use multiple variables (in this case, name and age) to store the returned values. This process is called "unpacking" the tuple.

You can think of tuples as a way to bundle multiple values together, like a small package. When you return a tuple from a function, you're essentially returning a package containing multiple values that can be unpacked and used as needed.

Returning Multiple Values Using Lists

Another way to return multiple values from a function is by using lists. A list is a collection of ordered, mutable elements, enclosed in square brackets. Lists are similar to tuples, but unlike tuples, they can be modified once created.

Here's an example that demonstrates how to return multiple values using lists:

def get_name_and_age():
    return ["Bob", 25]

name, age = get_name_and_age()
print(name)  # Output: Bob
print(age)   # Output: 25

In this example, we define a function called get_name_and_age that returns a list containing two values: a string "Bob" and an integer 25. When we call this function, we can use multiple variables (in this case, name and age) to store the returned values.

The main difference between using tuples and lists to return multiple values is that lists are mutable, which means you can modify their contents after they are created. This can be useful in some cases but may also introduce potential bugs if you accidentally modify the list when you shouldn't.

Returning Multiple Values Using Dictionaries

A dictionary is another data structure in Python that can be used to return multiple values from a function. Dictionaries are a collection of key-value pairs, enclosed in curly braces. Each key is unique and maps to a specific value.

Here's an example that demonstrates how to return multiple values using dictionaries:

def get_name_and_age():
    return {"name": "Charlie", "age": 28}

person = get_name_and_age()
print(person["name"])  # Output: Charlie
print(person["age"])   # Output: 28

In this example, we define a function called get_name_and_age that returns a dictionary containing two key-value pairs: "name" maps to "Charlie" and "age" maps to 28. When we call this function, we store the returned dictionary in a variable called person. To access the individual values, we use the keys as indexes, like person["name"] and person["age"].

Dictionaries can be useful for returning multiple values when the values have some meaning or relationship to each other. In this case, the keys help to describe the purpose of the values, making the code more readable and easier to understand.

Returning Multiple Values Using Custom Classes

In some cases, you might want to use custom classes to return multiple values from a function. This can be particularly useful when the values you are returning have a specific structure or set of behaviors that you want to encapsulate within a class.

Here's an example that demonstrates how to return multiple values using custom classes:

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

def get_name_and_age():
    return Person("David", 35)

person = get_name_and_age()
print(person.name)  # Output: David
print(person.age)   # Output: 35

In this example, we define a Person class with a constructor method that takes two arguments: name and age. We then define a function called get_name_and_age that returns an instance of the Person class with the provided name and age values. When we call this function, we store the returned Person object in a variable called person. To access the individual values, we use the dot notation, like person.name and person.age.

Using custom classes to return multiple values can be a good choice when you want to provide additional functionality or behavior associated with the returned values. It also helps to make your code more organized and easier to understand.

Conclusion

In this blog post, we've explored different ways to return multiple values in Python, including using tuples, lists, dictionaries, and custom classes. Each method has its own advantages and use cases, depending on the structure and requirements of your program.

Remember, when returning multiple values, it's important to choose a method that best fits the needs of your program and makes your code more readable and maintainable. By doing so, you'll create well-structured and efficient Python programs that are easy to understand and modify in the future.