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?
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
Is there an easy way to have a function return multiple variables that can be easily accessed?
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