Reputation: 8670
In Python I am trying to make a function that can accept 1 or more arguments. For simplicity let's say I want to make a function that prints all the arguments that are passed
def print_all(**arguments**):
print(arg1, arg2, ..., argN)
so print_all("A", "B")
would output AB
.
The number of arguments passed could be 1 or more strings.
What is the best way to do this?
Upvotes: 1
Views: 2455
Reputation: 3523
*args and **kwargs allow to pass any no of arguments, positional (*) and keyword (**) to the function
>>> def test(*args):
... for var in args:
... print var
...
>>>
For no of variable
>>> test("a",1,"b",2)
a
1
b
2
>>> test(1,2,3)
1
2
3
For list & dict
>>> a = [1,2,3,4,5,6]
>>> test(a)
[1, 2, 3, 4, 5, 6]
>>> b = {'a':1,'b':2,'c':3}
>>> test(b)
{'a': 1, 'c': 3, 'b': 2}
Upvotes: 2
Reputation: 48100
You are looking for the usage of *args
which allows you to pass multiple arguments to function without caring about the number of arguments you want to pass.
Sample example:
>>> def arg_funct(*args):
... print args
...
>>> arg_funct('A', 'B', 'C')
('A', 'B', 'C')
>>> arg_funct('A')
('A',)
Here this function is returning the tuple of parameters passed to your function.
For more details, check: What does ** (double star) and * (star) do for parameters?
Upvotes: 0
Reputation: 109686
Use the splat operator (*
) to pass one or more positional arguments. Then join them as strings in your function to print the result.
def print_all(*args):
print("".join(str(a) for a in args))
>>> print_all(1, 2, 3, 'a')
123a
Upvotes: 0