How to Use Methods with Variable Argument Lists in Python

By John Paul Mueller

Sometimes you create methods in Python that can take a variable number of arguments. Handling this sort of situation is something Python does well. Here are the two kinds of variable arguments that you can create:

  • *args: Provides a list of unnamed arguments.

  • **kwargs: Provides a list of named arguments.

The actual names of the arguments don’t matter, but Python developers use *args and **kwargs as a convention so that other Python developers know that they’re a variable list of arguments.

Notice that the first variable argument has just one asterisk (*) associated with it, which means the arguments are unnamed. The second variable has two asterisks, which means that the arguments are named. The following steps demonstrate how to use both approaches to writing an application.

  1. Open a Python File window.

    You see an editor in which you can type the example code.

  2. Type the following code into the window — pressing Enter after each line:

    class MyClass:
     def PrintList1(*args):
      for Count, Item in enumerate(args):
       print("{0}. {1}".format(Count, Item))
     def PrintList2(**kwargs):
      for Name, Value in kwargs.items():
       print("{0} likes {1}".format(Name, Value))
    MyClass.PrintList1("Red", "Blue", "Green")
    MyClass.PrintList2(George="Red", Sue="Blue",
         Zarah="Green")

    For the purposes of this example, you’re seeing the arguments implemented as part of a class method. However, you can use them just as easily with an instance method.

    Look carefully at PrintList1() and you see a new method of using a for loop to iterate through a list. In this case, the enumerate() function outputs both a count (the loop count) and the string that was passed to the function.

    The PrintList2() function accepts a dictionary input. Just as with PrintList1(), this list can be any length. However, you must process the items() found in the dictionary to obtain the individual values.

  3. Choose Run→Run Module.

    The individual lists can be of any length. In fact, playing with the code to see what you can do with it is a good idea. For example, try mixing numbers and strings with the first list to see what happens. Try adding Boolean values. The point is that using this technique makes your methods incredibly flexible if all you want is a list of values as input.

    image0.jpg