pass multiple arguments to a function

Viewed 1203

I wish to define a function that takes in 3 arguments, each of which is a variable-length list as follows:

a = [1,2,3]
b = [4,5,6]
c = [7,8,9]

def functionName(*args1,*args2,*args3):
    res1 = [i for i in args1]
    res2 = [i for i in args2]
    res3 = [i for i in args3]

    return res1,res2,res3

Now i wish to call functionName as follows:

functionName(a,b,c)

and get the three lists back.

However, I get hit with the following error:

File "<ipython-input-178-8d50368fdacf>", line 15
    def functionName(*args1,*args2,*args3):
                          ^
SyntaxError: invalid syntax

How can I implement a function whose arguments contain variable-length lists/arrays?

3 Answers

Why not just declare the function as follows:

def functionName(list1, list2, list3):
    res1 = [i for i in list1]
    res2 = [i for i in list2]
    res3 = [i for i in list3]

    return res1, res2, res3

I think that should work as you want it to.

When you pass in *args into a function that allows you to pass in more than the formally defined number of positional arguments, i.e. if you had something like

def func(a,b,*args):
    print(a,b)
    for arg in args:
       print(arg)

And then you called the function as

a = 10
b = 20

func(a, b, 35, 40)

your output would be

(10, 20)
35
40

You can also do something much simpler like this.

a = [1,2,3]
b = [4,5,6]
c = [7,8,9]

def functionName(*args1):
    for i in range(len(args1)):
        print (args1[i])
functionName(a,b,c)

This will result in:

[1, 2, 3]
[4, 5, 6]
[7, 8, 9]

Without the for loop, you can just give

print (args1)

It will give you the lists inside a tuple.

([1, 2, 3], [4, 5, 6], [7, 8, 9])

If you change it to:

functionName(a,c)

It will result in:

([1, 2, 3], [7, 8, 9])

Remember, *args1 will take in all the arguments you are sending and store them as a tuple.

See more details on *args and **kwargs here:

https://www.geeksforgeeks.org/args-kwargs-python/

https://realpython.com/python-kwargs-and-args/

As far as my understanding goes there you are passing 3 list objects to a function, so there is no need to type "*" before function parameter. List can be of variable size.

function(*args) is used when the number of parameters passed to the function are variable and unknown. Ex:

def function(*args):
    print(len(args))

    
>>> function(1,2,3,4)
4
>>> function(1,2)
2
Related