Variable arguments in python -- Possible or not? [duplicate] - python

This question already has answers here:
Can a variable number of arguments be passed to a function?
(6 answers)
Closed 8 years ago.
How do you write a function in Python with variable arguments into the function and return variable number of outputs? Is this even possible with the constraints?

You mean like this. This is quite similar to ellipses in Java. When supplied with a variable amount of arguments, you can unpack these arguments as a list which you can manipulate as you deem necessary.
def func(*args):
print len(args) # num of vars

yes you can, take a look at splat operator
def my_function(*a): #here a will be list or tuple depend wt u passed
# do your stuff with a
**a for dictionary

Related

How to pass arguments to a function when called by an array? [duplicate]

This question already has answers here:
Pass a list to a function to act as multiple arguments [duplicate]
(3 answers)
Closed 1 year ago.
I have a function and I have an array of arguments that I want to pass to the function when calling it like this:
def function(arg):
pass
function(arg)#call
but I want:
target = function
args = list()
output = call(function,args)
I know, that I can do it with Thread, but I want get a return to main Thread
Thread(target=target,args=args).start() # without output :(
The only possible solution I have come up with is
output = exec('function_name('+','.join(args))
P.S. The functions that I call have a variable number of positional and optional arguments
P.P.S. I can't edit function's code
If those are positional arguments you can use function(*args).

After recursion list not emptying [duplicate]

This question already has answers here:
"Least Astonishment" and the Mutable Default Argument
(33 answers)
Closed 2 years ago.
I'm doing some discrete mathematics stuff for a teacher, he asked me to try and do everything recursively. For some strange reason the list i'm using for a function is the same as it was the last time I called the function.
Here's my code:
def extended_euclidean_algorithm(a:int, b:int, equations=list()):
#This line is just for debugging and checking that my hipothesis was correct
print (len(equations))
if b==0:
return
if a<b:
b,a=a,b
quotient=a//b
remainder=a%b
equations.append(f"{a}={quotient}*{b}+{remainder}")
if extended_euclidean_algorithm(b, remainder, equations):
return equations
for i, equation in enumerate(equations):
equations[i]=equation.split('+')
equations[i][0]=equations[i][0].split('=')
equations[i][0]="-".join(equations[i][0])
equations[i]='='.join(equations[i])
return True
First time I call it, it's Ok. But second time I call it includes the numbers from the last time I called it.
Since you set the list in the arguments, by default the list exists and can be appended to.
You better use:
def extended_euclidean_algorithm(a:int, b:int, equations=None):
equations = equations if equations else []
In this way, equations - if not set - is None rather than an empty list.
Check out the pythontutor visualization here:

Express a method like a keyword [duplicate]

This question already has answers here:
Can you add new statements to Python's syntax?
(13 answers)
Closed 4 years ago.
How can I express a method (e.g. dir(os)) like a keyword (e.g. dir_ os)? Is it even possible?
The opposite is quite easy to achieve:
# `assert` expressed like a method
def assert_(x): assert x
assert_(1 == 1)
No, it's not possible. Parentheses are required in order to call a function or method.

Generalizing my python function [duplicate]

This question already has answers here:
Can a variable number of arguments be passed to a function?
(6 answers)
Closed 4 years ago.
I am trying to make my function be able to accept as many inputs or as little inputs as needed.
Currently I have 3 inputs that are hard coded (loc1, loc2, loc3). Is there a way to keep the inputs variable so if I just had 1 input, or if I have 5 inputs, my function can be flexible?
def np_array(loc1, loc2, loc3):
loc_a = np.array(loc1)
loc_b = np.array(loc2)
loc_c = np.array(loc3)
pressure_vector1 = np.subtract(loc_a, loc_c)
pressure_vector2 = np.subtract(loc_a, loc_b)
movement_vector = np.add(pressure_vector1, pressure_vector2)
return movement_vector
You can use *args or **kwargs for this.
In Python, the single-asterisk form of *args can be used as a parameter to send a non-keyworded variable-length argument list to functions. It is worth noting that the asterisk (*) is the important element here, as the word args is the established conventional idiom, though it is not enforced by the language.
The double asterisk form of **kwargs is used to pass a keyworded, variable-length argument dictionary to a function. Again, the two asterisks (**) are the important element here, as the word kwargs is conventionally used, though not enforced by the language.
Like *args, **kwargs can take however many arguments you would like to supply to it. However, **kwargs differs from *args in that you will need to assign keywords.
To learn more about this I recommend this awesome post
You could use default arguments to make the function more flexible like:
def np_array(loc1=None, loc2=None, loc3=None):
# ensure you don't use None type variables
if loc1 is None:
loc1 = 'sensibleDefaultValueGoesHere'
# repeat as often as needed before you proceed with the
# actual calculation ...

What is the difference in *args, **kwargs vs calling with tuple and dict? [duplicate]

This question already has answers here:
What does ** (double star/asterisk) and * (star/asterisk) do for parameters?
(25 answers)
Closed 6 years ago.
This is a basic question. Is there a difference in doing
def foo(*args, **kwargs):
"""standard function that accepts variable length."""
# do something
foo(v1...vn, nv1=nv1...nvn=nvn)
def foo(arg, kwargs):
"""convention, call with tuple and dict."""
# do something
mytuple = (v1, ..vn)
mydict = {nv1=nv1, ...nvn=nvn}
foo(mytuple, mydict)
I could do the same thing with both, except that the later has a weird convention of creating a tuple and dictionary. But basically is there a difference? I can solve the same computational problem of handling infinite things because dict and tuple can take care of that for me anyway?
Is this more of an idiomatic part of Python i.e a good Syntactic Sugar for things that you do anyway? I.e function is going to handle this for you!
PS: Not sure of so many downvotes though I agree this is a copy of Why use packed *args/**kwargs instead of passing list/dict? and probably it should be corrected in the duplicate information. And that question has recieved upvotes. So am I being downvotes for not being able to find that?
args and kwargs are just names.
What really matters here is the * and **.
In your second example you can only call the function with 2 arguments, against the first example where you can call the function with basically infinite arguments.

Categories