1

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?

Bijan
  • 7,737
  • 18
  • 89
  • 149

4 Answers4

2

*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}

For detail

Kallz
  • 3,244
  • 1
  • 20
  • 38
0

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?

Moinuddin Quadri
  • 46,825
  • 13
  • 96
  • 126
0

Simply this:

def print_all(*args):
    for arg in args:
        print(arg)
Julien
  • 13,986
  • 5
  • 29
  • 53
0

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
Alexander
  • 105,104
  • 32
  • 201
  • 196