Python
function
multiple values
programming
best practices

Alternatives for returning multiple values from a Python function

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

In Python, functions are designed to return a single value object. However, there are situations where returning multiple values is not only convenient but also necessary. Various alternatives exist in Python to return multiple values, each with its pros and cons. This article will cover these alternatives, providing technical explanations and examples for better understanding.

1. Using Tuples

Returning a tuple is one of the most common and intuitive ways to return multiple values in Python. Tuples are immutable collections that can hold multiple items.

Example:

python
1def get_user_info():
2    name = "Alice"
3    age = 30
4    return name, age
5
6# Usage
7user_name, user_age = get_user_info()
8print(user_name)  # Alice
9print(user_age)   # 30

Pros:

  • Simple and Intuitive: Easy to implement and understand.
  • Immutable: The returned data cannot be altered accidentally.

Cons:

  • Unpacking Required: The caller must unpack the returned values appropriately.
  • Lack of Readability: The returned values lack descriptive context if not properly documented.

2. Using Lists

Lists can also be used to return multiple values. Unlike tuples, lists are mutable.

Example:

python
1def get_fruits():
2    fruits = ["apple", "banana", "cherry"]
3    return fruits
4
5# Usage
6fruit_list = get_fruits()
7for fruit in fruit_list:
8    print(fruit)

Pros:

  • Flexibility: Lists are mutable, allowing for changes after they are returned.
  • Easy to Iterate: Can be looped through easily.

Cons:

  • Mutable: Unintended changes might occur if not handled carefully.
  • Type Homogeneity: Typically used when returning items of the same type.

3. Using Dictionaries

Dictionaries can be used when you need a more descriptive way of returning multiple related values.

Example:

python
1def get_book_info():
2    book_info = {
3        "title": "1984",
4        "author": "George Orwell",
5        "published": 1949
6    }
7    return book_info
8
9# Usage
10info = get_book_info()
11print(info["title"])        # 1984
12print(info["author"])       # George Orwell

Pros:

  • Descriptive: Keys provide context to each value.
  • Flexibility: Easy to add more key-value pairs as needed.

Cons:

  • Overhead: More verbose compared to other methods for a small number of values.

4. Using Data Classes (Python 3.7+)

Data classes provide a neat way to bundle multiple attributes in a class-like structure. They are ideal for returning a group of related data.

Example:

python
1from dataclasses import dataclass
2
3@dataclass
4class Person:
5    name: str
6    age: int
7
8def get_person_info():
9    return Person(name="Alice", age=30)
10
11# Usage
12person = get_person_info()
13print(person.name)  # Alice
14print(person.age)   # 30

Pros:

  • Readability: Code is self-documenting with annotated fields.
  • Type Safety: Offers type hinting for better maintenance.

Cons:

  • Python 3.7+ Requirement: Not available in earlier Python versions.
  • Slightly More Overhead: Involves defining a class structure.

5. Using Named Tuples

Named tuples offer the advantages of both dictionaries and regular tuples: readability and immutability.

Example:

python
1from collections import namedtuple
2
3Person = namedtuple('Person', ['name', 'age'])
4
5def get_person_data():
6    return Person(name="Alice", age=30)
7
8# Usage
9person = get_person_data()
10print(person.name)  # Alice
11print(person.age)   # 30

Pros:

  • Readability: Attributes are accessible by name.
  • Immutable: Prevents accidental data modification.

Cons:

  • Static Structure: Cannot easily add additional fields later.

Summary Table

MethodProsCons
TuplesSimple, ImmutableRequires Unpacking, Less Descriptive
ListsFlexible, Easy to IterateMutable, Typically Homogeneous Types
DictionariesDescriptive, FlexibleVerbose
Data ClassesReadable, Type SafetyPython 3.7+, Slight Overhead
Named TuplesReadable, ImmutableStatic Structure

Additional Details

Choosing the Right Approach

The choice of method largely depends on the context and requirements of your application:

  • Use tuples when returning a small, fixed set of different types.
  • Choose lists when the number of values is variable or dynamically generated.
  • Opt for dictionaries when you need named access to values, improving code readability.
  • Data classes are ideal for complex data structures with clear type definitions.
  • Named tuples offer an excellent middle ground with named access and immutability.

Understanding these options and their implications allows you to write cleaner, more maintainable Python code. Whether you favor immutability, descriptive structuring, or flexibility, Python offers the tools needed to tailor function returns to your specific needs.


Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions