Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use a single variable instead of passing multiple Arguments in Python

Tags:

python

Say for example if I have a method which takes multiple inputs like below:

def SumOf(Arg1,Arg2,Arg3):
    Sum = Arg1+Arg2+Arg3
    return sum

I have the values of Arg1, Arg2, Arg3 in a list and I want to access the method

Arguments = Arg1 + "," +  Arg2 + "," + Arg 3

I want to use the variable Arguments to call the method SumOf

SumOf(Arguments)

But I get the following error:

SumOf() takes exactly 3 arguments (1 given)

Note: The above is just an example, I need this for executing different methods based on the method name and arguments.

Please help.

like image 358
Karthick Avatar asked Apr 19 '13 13:04

Karthick


People also ask

Can we take more than one value as parameter to a Python function?

We can pass multiple arguments to a python function by predetermining the formal parameters in the function definition.

How do you pass a variable as an argument in Python?

The special syntax *args in function definitions in python is used to pass a variable number of arguments to a function. It is used to pass a non-key worded, variable-length argument list. The syntax is to use the symbol * to take in a variable number of arguments; by convention, it is often used with the word args.

What are the two methods of passing arguments to functions in Python?

By default, arguments may be passed to a Python function either by position or explicitly by keyword.

How do you make an argument optional in Python?

You can define Python function optional arguments by specifying the name of an argument followed by a default value when you declare a function. You can also use the **kwargs method to accept a variable number of arguments in a function. To learn more about coding in Python, read our How to Learn Python guide.


2 Answers

Arguments = 1, 2, 3
SumOf(*Arguments)

(*) operator will unpack the arguments to multiple parameters.

like image 192
thavan Avatar answered Oct 31 '22 19:10

thavan


Looks like there's quite a few issues with your code. The line...

Arguments = Arg1 + "," +  Arg2 + "," + Arg3

...suggests Arg1, Arg2 and Arg3 are strings, which you're trying to concatenate into a single, comma-separated, string.

In order for the SumOf function to work, it will need to be passed integer values, so if Arg1, Arg2 and Arg3 are strings, you'll need to convert them to integers first with the int() function, and pack them into a tuple, with something like...

Arguments = (int(Arg1), int(Arg2), int(Arg3))

...at which point you can call the function with either...

SumOf(*Arguments)

...or...

apply(SumOf, Arguments)

Additionally, you'll need to change the line...

return sum

...to...

return Sum

...otherwise you'll end up returning a reference to Python's built-in sum() function.

like image 32
Aya Avatar answered Oct 31 '22 20:10

Aya