Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return more than one value from a function in Python? [duplicate]

How to return more than one variable from a function in Python?

like image 597
user46646 Avatar asked Jan 08 '09 09:01

user46646


People also ask

Can we return 2 values from a function in Python?

Python functions can return multiple values. These values can be stored in variables directly. A function is not restricted to return a variable, it can return zero, one, two or more values.

How can I return multiple values from a function?

We can return more than one values from a function by using the method called “call by address”, or “call by reference”. In the invoker function, we will use two variables to store the results, and the function will take pointer type data.


2 Answers

You separate the values you want to return by commas:

def get_name():    # you code    return first_name, last_name 

The commas indicate it's a tuple, so you could wrap your values by parentheses:

return (first_name, last_name) 

Then when you call the function you a) save all values to one variable as a tuple, or b) separate your variable names by commas

name = get_name() # this is a tuple first_name, last_name = get_name() (first_name, last_name) = get_name() # You can put parentheses, but I find it ugly 
like image 136
Cristian Avatar answered Sep 22 '22 14:09

Cristian


Here is also the code to handle the result:

def foo (a):     x=a     y=a*2     return (x,y)  (x,y) = foo(50) 
like image 30
Staale Avatar answered Sep 22 '22 14:09

Staale