3

So in java you can do something like this if you don't know how many parameters you are going to get

private void testMethod(String... testStringArray){

}

How can I do something like this in python

as I can't do something like this right?

def testMethod(...listA):
Benjamin Oakes
  • 12,262
  • 12
  • 65
  • 83
FabianCook
  • 20,269
  • 16
  • 67
  • 115

2 Answers2

7

Are you talking about variable length argument lists? If so, take a look at *args, **kwargs.

See this Basic Guide and How to use *args and **kwargs in Python

Two short examples from [1]:

Using *args:

def test_var_args(farg, *args):
    print "formal arg:", farg
    for arg in args:
        print "another arg:", arg

test_var_args(1, "two", 3)

Results:

formal arg: 1
another arg: two
another arg: 3

and using **kwargs (keyword arguments):

def test_var_kwargs(farg, **kwargs):
    print "formal arg:", farg
    for key in kwargs:
        print "another keyword arg: %s: %s" % (key, kwargs[key])

test_var_kwargs(farg=1, myarg2="two", myarg3=3)

Results:

formal arg: 1
another keyword arg: myarg2: two
another keyword arg: myarg3: 3

Quoting from this SO question What do *args and **kwargs mean?:

Putting *args and/or **kwargs as the last items in your function definition’s argument list allows that function to accept an arbitrary number of anonymous and/or keyword arguments.

Community
  • 1
  • 1
Levon
  • 138,105
  • 33
  • 200
  • 191
6

Sounds like you want:

def func(*args):
      # args is a list of all arguments

This like a lot of other such information is covered in the Python tutorial, which you should read.

BrenBarn
  • 242,874
  • 37
  • 412
  • 384