1

I have a list of variables that I want to send to my function. (so the function works based on the values on those variables).

One way is to pass each variable separately in the function like this:

def my_function(var1, var2, var3, var4, ..., varn):
   output = var1 + var2 + var3 + var4 + .... + varn

However, I wonder if I can write such a thing:

def my_function(parameters):
    output = parameters.var1 + parameters.var2 + ... + parameters.varn

That is, somehow is there any way to wrap all variables in one variable, and then call them like this?

I know the above python codes are not correct, I just want to express my question.

Thanks in advance

4
  • pass those variable in a list and then do summation ? Commented Nov 30, 2021 at 4:53
  • 2
    Maybe you may use **kwargs? realpython.com/python-kwargs-and-args Commented Nov 30, 2021 at 4:54
  • Stop thinking in terms of variables. You don't pass variables, you pass objects. Put your objects into another object, like a list, or a dict, or as members of an instance of a user-defined class Commented Nov 30, 2021 at 4:57
  • Alternatively, use some sort of variadic argument, which will basically put your arguments into a data structure for you, a tuple or a dict Commented Nov 30, 2021 at 4:58

1 Answer 1

3

There are many options. You have to determine which way fits your case.

Option 1. Getting multiple arguments by a single asterisk

def my_function(*args):
    output = sum(args)

    # SAME WITH
    # output = args[0] + args[1] + ... + args[n]
    #
    # PASSING ARGUMENTS EXAMPLE
    # my_function(10, 20, 10, 50)

Option 2. Getting keyword arguments by double asterisk

def my_function(**kwargs):
    output = sum(kwargs.values())
    
    # SAME WITH
    # output = kwargs["var0"] + kwargs["var1"] + ... + kwargs["varn"]
    #
    # PASSING ARGUMENTS EXAMPLE
    # my_function(var0=10, var1=20, var2=15)

Option 3. Getting an argument as a list

def my_function(list_arg):
    output = sum(list_arg)

    # SAME WITH
    # output = list_arg[0] + list_arg[1] + ... + list_arg[n]
    #
    # PASSING ARGUMENTS EXAMPLE
    # my_function([1, 10, 3, -10])

Option 4. Getting an argument as a dictionary

def my_function(dict_arg):
    output = sum(dict_arg.values())

    # SAME WITH
    # output = kwargs["var0"] + kwargs["var1"] + ... + kwargs["varn"]
    #
    # PASSING ARGUMENTS EXAMPLE
    # my_function({"var0":5, "var1":10, "var2":3})
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.