How to Return Multiple Values in Python (and When to Use Each Method)

Kimberly FesselKimberly Fessel

Programming languages give us the amazing ability to perform repetitive tasks with minor modifications by writing . You can build such functions in Python and design them to return zero, one, two, or more values.

In this article, we’ll show you several different ways to get multiple values from a Python function. We’ll compare the merits of each and warn you of a few common “gotchas” to avoid. Let’s begin with a quickstart demonstration.

Returning Multiple Values From a Function

Defining a function in Python is as simple as typing the keyword def and giving your function a name. You’ll write code with instructions for what your function should do, and if you’d like, you can have your function give information back with a return. Here’s a code example of a function that takes in two arguments and returns their sum when called:

python
def add_two(x, y):    total = x + y    return totalprint(add_two(2, 3))# Expected result:# 5

If you’d like your function to return more than one output, separate the values with commas in your return statement. For instance, this function computes both the sum and product of the inputs:

python
def add_multiply_two(x, y):    total = x + y    product = x * y    return total, productprint(add_multiply_two(2, 3))# Expected result:# (5, 6)

Python automatically packs the returned values into a . That tuple contains both outputs in the same order as you list them in return.

The tuple is the default and generally most Pythonic way to return more than one value, but there are a few other solutions worth mentioning as well.

Option 1 — Tuple

Python functions return exactly one , so to get more than one value, you’ll need to package them up in a larger . More often than not, you’ll see multiple values returned as a tuple. The tuple data type is , and it preserves the order of elements as defined at creation, which turns out to be perfect for packaging related values together.

Use the return Statement for Multiple Return Values

You can put multiple values, separated by a comma, in return. Python implicitly creates a tuple containing all your return items for you, so you can, but do not need to, enclose those values in parentheses.

Here’s a function called analyze_text() that outputs the length, word count, and an uppercase version of an input text string:

python
def analyze_text(text):    length = len(text)    word_count = len(text.split())    upper = text.upper()    return length, word_count, upperprint(analyze_text("Now returning multiple values."))# Expected result:# (30, 4, 'NOW RETURNING MULTIPLE VALUES.')

Unpacking Multiple Variables from the Returned Tuple

Because Python automatically packages your values up in a tuple, you can either access the individual values by index position or unpack them to have direct access. Here’s each option in code:

  1. Save the resulting tuple as a single variable and reference the individual items by index position.

python
# Option 1 - Save as a single itemsummary = analyze_text("Now returning multiple values.")print(f"There are {summary[1]} words in the string.")# Expected result:# There are 4 words in the string
  1. Save each value individually for immediate access.

python
# Option 2 - Save individualslength, word_count, upper = analyze_text("Now returning multiple values.")print(f"There are {word_count} words in the string.")# Expected result:# There are 4 words in the string

This option works well for simple, fixed-structure returns. Keep in mind, however, the number of comma-separated variables on the left must match the number of returned values, or Python will raise a ValueError. Also note the significance of order here. The returned tuple contains no labels. You’ll need to remember the first value contains the length and so on to avoid errors.

Option 2 — Named Tuple

For improved readability, consider sending back several values in a . The namedtuple data type comes from the built-in collections module. It’s immutable and retains order like regular tuples, but it also allows you to look up elements by name with dot notation.

You can store multiple values in a named tuple and have your function output it as a single Python object. Here’s code to once again analyze a text string, but with the results now stored in a named tuple:

python
from collections import namedtupleAnalysis = namedtuple("Analysis", ["length", "word_count", "upper"])def analyze_text(text):    return Analysis(        len(text),        len(text.split()),        text.upper()    )summary = analyze_text("Now returning multiple values.")print(summary)print(summary.length)print(summary.word_count)# Expected result:# Analysis(length=30, word_count=4, upper='NOW RETURNING MULTIPLE VALUES.')# 30# 4

Named tuples are good for fixed-structure situations where clarity matters. You no longer need to remember the exact position of each element because you can refer to it by name. They are a nice middle ground between plain tuples (fast but positional) and full classes (flexible but more complex).

Option 3 — Dataclass for Complex Return Values

Moving beyond tuples, allow greater flexibility for multiple return values. They come from the dataclasses module, and you can define them with a simple @dataclass . They’re designed for structured objects but offer more capability than named tuples.

Here’s what analyze_text() looks like with a dataclass:

python
from dataclasses import dataclass@dataclassclass Analysis:    length: int    word_count: int    upper: strdef analyze_text(text):    return Analysis(        length=len(text),        word_count=len(text.split()),        upper=text.upper()    )summary = analyze_text("Now returning multiple values.")print(summary)print(summary.length)print(summary.word_count)# Expected result:# Analysis(length=30, word_count=4, upper='NOW RETURNING MULTIPLE VALUES.')# 30# 4

Unlike tuples, dataclass objects are by default, meaning you can modify their values after creation.

python
summary.word_count = 10print(summary)# Expected result:# Analysis(length=30, word_count=10, upper='NOW RETURNING MULTIPLE VALUES.')

You can also include default values and even add methods for more advanced behavior.

Option 4 — Dictionary

Dictionaries give you yet another solution for returning several results from a single function call. They store information in key-value pairs, so you can look up data by descriptive keys instead of position. Dictionaries are mutable, so you can easily add, remove, or change fields on the fly.

For example, the analyze_text() function could return a dictionary of information with the computed values when you call it:

python
def analyze_text(text):    return {        "length": len(text),        "word_count": len(text.split()),        "upper": text.upper()    }summary = analyze_text("Now returning multiple values.")print(summary)print(summary["length"])print(summary["word_count"])# Expected result:# {'length': 30, 'word_count': 4, 'upper': 'NOW RETURNING MULTIPLE VALUES.'}# 30# 4

Give dictionaries a try if your return structure is not fixed or may evolve over time. They’re commonly used in data processing tasks and APIs as they map naturally to JSON-like output.

The Quick-Reference Comparison Table

Here’s a handy table for you to compare and contrast the techniques we covered for returning multiple values in Python:

Technique

Mutable/Immutable

Element Reference

Readability

Use Case

Gotchas

Tuple

Immutable

Position

Medium

Simple, fixed return values

Easy to mix order when extracting values

Named Tuple

Immutable

By name (dot notation) or position

High

Fixed structure where clarity matters

Still rigid; no easy evolution of structure

Dataclass

Mutable (by default)

By name (dot notation)

High

Structured, evolving return data

Slightly more overhead

Dictionary

Mutable

By key (square brackets)

High

Flexible or optional return values, API-style data

Keys can be mistyped; no enforced structure

AI Tutor: Show me Python examples of getting more than one value from a function with lists and generators.

Common Errors and Best Practices for Python Functions

With the multiple ways to package results, there’s bound to be a few things to watch out for in your code. Keep these tips in mind to avoid errors and make the most of your data structures.

Mismatched Unpacking of Return Values

Perhaps the most common error regarding this topic is having too few or too many comma-separated variables when attempting to unpackage your returned results. For example, if you write:

a, b = func()

Python expects exactly two return values for the two variables, a and b. You’ll get an error for any more or less than expected.

When the function actually gives you more values than you unpacked, you’ll get a ValueError:

python
def func():    return 1, 2, 3a, b = func()# Expected result:# ValueError: too many values to unpack (expected 2)

Likewise, you’ll also get an error if the functions returns too few outputs:

python
def func():    return (1,)a, b = func()# Expected result:# ValueError: not enough values to unpack (expected 2, got 1)

If you receive a ValueError, double-check that the number of variables is equal to the number of returned values.

Using _ to Skip Outputs

You’ll need to assign the exact number of outputs a function provides if you choose to extract the values, but if you don’t need a particular output, you can assign it to the throwaway variable _. Developers understand a single underscore as a placeholder for a value you don’t care about.

To test this out, we can assign the uppercase version of our text from analyze_text() to _ if we don’t need it:

python
def analyze_text(text):    length = len(text)    word_count = len(text.split())    upper = text.upper()    return length, word_count, upperlength, word_count, _ = analyze_text("You don't need this uppercase.")print(word_count)print(_)# Expected result:# 5# "YOU DON'T NEED THIS UPPERCASE."

Choosing the Simplest Structure that Works

Even with the comparison chart, you may still be wondering when to choose each of the options discussed in this article. Ultimately, you’ll want to pick the simplest technique that supports your project. Start with the simple tuple and increase the complexity as needed. Specifically:

  • Use a tuple for simple, fixed outputs

  • Use a named tuple when readability is important

  • Use a dataclass for structured data when you expect to append fields or methods later

  • Use a dictionary when fields are optional or dynamic

Wrapping Up

When it’s time to return multiple values, Python allows several different techniques. Remember that functions return exactly one object, so you’ll need to package your values into a collection of some sort. Separate your values with commas in the return statement, and Python will automatically wrap them into a tuple. If you need additional readability or flexibility, consider named tuples or dataclasses, and move on to dictionaries when fields are optional or may change over time.

No matter which way you decide to package up your return values, you can learn more by interacting with the AI Tutor. This prompt should get you going:

Join the Community

roadmap.sh is the 6th most starred project on GitHub and is visited by hundreds of thousands of developers every month.

Rank  out of 28M!

357K

GitHub Stars

Star us on GitHub
Help us reach #1

+90kevery month

+2.8M

Registered Users

Register yourself
Commit to your growth

+2kevery month

48K

Discord Members

Join on Discord
Join the community

RoadmapsGuidesFAQsYouTube

roadmap.shby@nilbuild

Community created roadmaps, best practices, projects, articles, resources and journeys to help you choose your path and grow in your career.

© roadmap.sh·Terms·Privacy·

ThewNewStack

The top DevOps resource for Kubernetes, cloud-native computing, and large-scale development and deployment.