Monday, March 17, 2014

*Any Number of Arguments

*Any Number of Arguments


Something really cool that I came across today is putting a "*" in the argument in a function. It allows for you use any number of arguments for that function which is really cool and useful!

The the following example:

def add_all_values(*values):
    total = 0
    for x in values:
        total += x
    return total

add_all_values can take any number of  arguments:

>>> add_all_values()
0
>>> add_all_values(1)
1
>>> add_all_values(1, 2)
3
>>> add_all_values(1, 2, 3)
6
>>> add_all_values(1, 2, 3, 4)
10
>>> add_all_values(1, 2, 3, 4, 5)
15
>>> add_all_values(1, 2, 3, 4, 5, 6)
21
>>> add_all_values(1, 2, 3, 4, 5, 6, 7)
28
>>> add_all_values(1, 2, 3, 4, 5, 6, 7, 8)
36
>>> add_all_values(1, 2, 3, 4, 5, 6, 7, 8, 9)
45
>>> add_all_values(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)

55

What is really fascinating is that this can be used to increase the versatility of higher order functions. Take the following examples:

def test_values(func, *values):
    a = []
    for x in values:
        a.append(func(x))
    return a

def square_value(value):
    return (value**2)

def cube_value(value):
    return (value**3)

def value_to_power_of_value(value):
    return (value**value)

So what's really cool is that now, we can use different number of arguments in the higher order function when we call the various lower order ones!

>>> test_values(square_value, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
>>> test_values(cube_value, 1, 2, 3, 4, 5)
[1, 8, 27, 64, 125]
>>> test_values(value_to_power_of_value, 1, 2, 3, 4)
[1, 4, 27, 256]

No comments:

Post a Comment