Python Newbie: returning multiple Int / String results in Python
I have a function that has several outputs, all of which are "native", i.e. integers and strings. For example, let's say I have a function that parses a string and finds both the word count and the average word length.
In C / C ++, I would use @ to pass 2 parameters to a function. In Python, I'm not sure which is the correct solution, because integers and strings are not passed by reference, but by value (at least that's what I understand from trial and error), so the following code won't work: / p >
def analyze(string, number_of_words, average_length):
... do some analysis ...
number_of_words = ...
average_length = ...
If I do this, the values outside the scope of the function do not change. I am currently using a dictionary like this:
def analyze(string, result):
... do some analysis ...
result['number_of_words'] = ...
result['average_length'] = ...
And I am using the function like this:
s = "hello goodbye"
result = {}
analyze(s, result)
However, it is not. What's the correct Python way to achieve this? Note that I only mean cases where the function returns 2-3 results, not dozens of results. Also, I am a complete Python newbie, so I know that maybe I am missing something trivial ...
thanks
a source to share
python has a statement return
that allows you to do the following:
def func(input):
# do calculation on input
return result
s = "hello goodbye"
res = func(s) # res now a result dictionary
but you don't need to have at all result
, you can return multiple values:
def func(input):
# do work
return length, something_else # one might be an integer another string, etc.
s = "hello goodbye"
length, something = func(s)
a source to share
If you return variables in your function like this:
def analyze(s, num_words, avg_length):
# do something
return s, num_words, avg_length
Then you can call it like this to update the passed parameters:
s, num_words, avg_length = analyze(s, num_words, avg_length)
But for your example function, this would be better:
def analyze(s):
# do something
return num_words, avg_length
a source to share
In python, you don't change parameters in a C / C ++ method (passing them by reference or through a pointer and making the changes in situ). There are some reasons like inmutable string objects in python. The correct solution is to revert the changed parameters into a tuple (as suggested by SilentGhost) and rebuild the variables with new values.
a source to share