How to Return Multiple Values from a Function in Python

Modified: | Tags: Python

This article explains how to return multiple values from a function in Python.

For an introduction to the basics of functions in Python, refer to the following article.

Return multiple values using commas

In Python, you can return multiple values by simply separating them with commas in the return statement.

For example, you can define a function that returns a string and an integer as follows:

def test():
    return 'abc', 100

In Python, comma-separated values are treated as tuples even without parentheses, unless parentheses are required by syntax. Therefore, the function in the example above returns a tuple.

Note that it is actually the comma which makes a tuple, not the parentheses. The parentheses are optional, except in the empty tuple case, or when they are needed to avoid syntactic ambiguity.
Built-in Types - Tuples — Python 3.13.3 documentation

result = test()

print(result)
print(type(result))
# ('abc', 100)
# <class 'tuple'>

Each element in the returned tuple has the data type defined in the function.

print(result[0])
print(type(result[0]))
# abc
# <class 'str'>

print(result[1])
print(type(result[1]))
# 100
# <class 'int'>

Naturally, accessing an index beyond the number of returned values will raise an error.

# print(result[2])
# IndexError: tuple index out of range

You can unpack multiple return values and assign them to separate variables.

a, b = test()

print(a)
# abc

print(b)
# 100

The same applies to three or more return values.

def test2():
    return 'abc', 100, [0, 1, 2]

a, b, c = test2()

print(a)
# abc

print(b)
# 100

print(c)
# [0, 1, 2]

Return a list from a function

By using [], you can return a list instead of a tuple.

def test_list():
    return ['abc', 100]

result = test_list()

print(result)
print(type(result))
# ['abc', 100]
# <class 'list'>

Related Categories

Related Articles