Hello World!

Passing arguments as a list

In the Author Forum on the Manning page for the book, someone asked about passing arguments to a function as a list. Since posting code on that forum doesn’t work well, I thought I would post the answer here on this blog.

If you are passing a number of arguments to a function, you could pass them as individual arguments, like this:

def printMyLuckyNumbers(num1, num2, num3, num4, num5):
    print "Here are your lucky numbers:"
    print num1, num2, num3, num4, num5


Then, you would call the function, like this:

printMyLuckyNumbers(3, 7, 10, 14, 27)


But that has a couple of disadvantages. First, if there are a lot of arguments, it gets messy to type all the variable names. Second, you might not know ahead of time how many arguments you want to pass.

So, another way, that solves both those problems, is to pass a list of arguments instead, like this:

def printMyLuckyNumbers(myNums):
    print "Your lucky numbers are:"
    for num in myNums:
        print num,


Then you would call the function like this:

myLuckyNumbers = [3, 7, 10, 14, 27]
printMyLuckyNumbers(myLuckyNumbers)


In the first example, you are passing 5 separate arguments. In the second example, you are passing a single list. That list happens to have 5 items, in this example. But it would work with any number of items. For example, this would work just fine when calling the second version of the function:

myLuckyNums = [2, 3, 5, 7, 10, 27, 32, 45]
printMyLuckyNumbers(myLuckyNums)


These are very simple examples. You can pass things more complicated than lists. You can pass nested lists (lists of lists, or two-dimensional lists). You can pass objects, which can contain any data structure you care to define. You can pass lists of objects or objects containing lists (or dictionaries, or any other Python data type).