Python Newbie: Returning Multiple Int/String Results in Python
I have a function that has several outputs, all of which "native", i.e. integers and strings. For example, let's say I have a function that analyzes a string, and finds both the number of words and the average length of a word.
In C/C++ I would use @ to pass 2 parameters to the function. In Python I'm not sure what's the right solution, because integers and strings are not passed by reference but by value (at least this is what I understand from trial-and-error), so the following code won't work:
def analyze(string, number_of_words, average_length):
... do some analysis ...
number_of_words = ...
average_length = ...
If i do the above, the values outside the scope of the function don't change. What I currently do is use a dictionary like so:
def analyze(string, result):
... do some analysis ...
result['number_of_words'] = ...
result['average_length'] = ...
And I use the function like this:
s = "hello goodbye"
result = {}
analyze(s, result)
However, that does not feel right. What's the correct Pythonian way to achieve this? Please note I'm referring only to cases where the function returns 2-3 results, not tens of results. Also, I'm a complete newbie to Python, so I know I may be missing something trivial here...
Thanks
Asked by: Sawyer504 | Posted: 30-11-2021
Answer 1
python has a return
statement, which allows you to do the follwing:
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 result
at all, you can return a few values like so:
def func(input):
# do work
return length, something_else # one might be an integer another string, etc.
s = "hello goodbye"
length, something = func(s)
Answered by: Rubie599 | Posted: 01-01-2022
Answer 2
If you return the 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 parameters that were passed:
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
Answered by: Cadie161 | Posted: 01-01-2022
Answer 3
In python you don't modify parameters in the C/C++ way (passing them by reference or through a pointer and doing modifications in situ).There are some reasons such as that the string objects are inmutable in python. The right thing to do is to return the modified parameters in a tuple (as SilentGhost suggested) and rebind the variables to the new values.
Answered by: Brooke337 | Posted: 01-01-2022Answer 4
If you need to use method arguments in both directions, you can encapsulate the arguments to the class and pass object to the method and let the method use its properties.
Answered by: Kellan911 | Posted: 01-01-2022Similar questions
python - Django: Arbitrary number of unnamed urls.py parameters
I have a Django model with a large number of fields and 20000+ table rows. To facilitate human readable URLs and the ability to break down the large list into arbitrary sublists, I would like to have a URL that looks like this:
/browse/<name1>/<value1>/<name2>/<value2>/ .... etc ....
where 'name' maps to a model attribute and 'value' is the search criteria for that...
python - variables as parameters in field options
I want to create a model, that will set editable=False on creation, and editable=True on editing item. I thought it should be something like this:
home = models.ForeignKey(Team, editable=lambda self: True if self.id else False)
But it doesn't work. Maybe something with overriding the init can help me, but i don't sure what can do the trick. I know i can check for self.id...
c# - How to analyse .exe parameters inside the program?
I have a program that can have a lot of parameters (we have over +30 differents options).
Example:
myProgram.exe -t alpha 1 -prod 1 2 -sleep 200
This is 3 Commands (from command pattern object at the end) that each contain some parameters. Inside the code we parse all command (start with -) and get a list of string (split all space) for the parameters. So in fact, we have : string-->Collection ...
python - Default parameters to actions with Django
Is there a way to have a default parameter passed to a action in the case where the regex didnt match anything using django?
urlpatterns = patterns('',(r'^test/(?P<name>.*)?$','myview.displayName'))
#myview.py
def displayName(request,name):
# write name to response or something
I have tried setting the third parameter in the urlpatterns to a dictionary containing ' and giving...
python - Loop function parameters for sanity check
I have a Python function in which I am doing some sanitisation of the input parameters:
def func(param1, param2, param3):
param1 = param1 or ''
param2 = param2 or ''
param3 = param3 or ''
This caters for the arguments being passed as None rather than empty strings. Is there an easier/more concise way to loop round the function parameters to apply such an expression to ...
python - How can I pass all the parameters to a decorator?
I tried to trace the execution of some methods using a decorator. Here is the decorator code:
def trace(func):
def ofunc(*args):
func_name = func.__name__
xargs = args
print "entering %s with args %s" % (func_name,xargs)
ret_val = func(args)
print "return value %s" % ret_val
print "exiting %s" % (func_nam...
Print out list of function parameters in Python
Is there a way to print out a function's parameter list?
For example:
def func(a, b, c):
pass
print_func_parametes(func)
Which will produce something like:
["a", "b", "c"]
python - How to create a decorator that can be used either with or without parameters?
I'd like to create a Python decorator that can be used either with parameters:
@redirect_output("somewhere.log")
def foo():
....
or without them (for instance to redirect the output to stderr by default):
@redirect_output
def foo():
....
Is that at all possible?
Note that I'm not looking for a different solution to the problem of redirectin...
python - Scope of lambda functions and their parameters?
This question already has answers here:
sql - How do you make the Python Msqldb module use ? in stead of %s for query parameters?
MySqlDb is a fantastic Python module -- but one part is incredibly annoying.
Query parameters look like this
cursor.execute("select * from Books where isbn=%s", (isbn,))
whereas everywhere else in the known universe (oracle, sqlserver, access, sybase...)
they look like this
cursor.execute("select * from Books where isbn=?", (isbn,))
This means that if you ...
Still can't find your answer? Check out these communities...
PySlackers | Full Stack Python | NHS Python | Pythonist Cafe | Hacker Earth | Discord Python