Returning multiple values in a python function

Question:

Is there an easy way to have a function return multiple variables that can be easily accessed?

Asked By: Cease

||

Answers:

The usual way to do this is a tuple, which can just be used with return:

>>> def multi_return():
        return 1, 2, 3

>>> multi_return()
(1, 2, 3)

You can use tuple unpacking to bind the return values to separate names:

>>> a, b, c = multi_return()
>>> a
1
>>> b
2
>>> c
3

Alternatively, you can return a single list, which will be treated much the same way:

>>> def list_return():
        return [1, 2, 3]

>>> list_return()
[1, 2, 3]
>>> a, b, c = list_return()
>>> b
2
Answered By: jonrsharpe
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.