Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Variable Argument to functions

I am learning Python and came across variadic arguments. I don't understand the output that the following code produces:

_list = [11,2,3]
def print_list(*args):
    for value in args:
        a = value * 10
        print(a)
print_list(_list)

When I run the program, I get:

[11, 2, 3, 11, 2, 3, 11, 2, 3, 11, 2, 3, 11, 2, 3, 11, 2, 3, 11, 2, 3, 11, 2, 3, 11, 2, 3, 11, 2, 3]

From what I understand, value holds one single element from the _list array, multiplying it by 10 would produce the list [110, 20, 30]. Why does the output differ?

like image 576
Tesla Avatar asked Jul 08 '26 21:07

Tesla


1 Answers

Because the parameter to your function is *args (with a *), your function actually receives a tuple of the passed in arguments, so args becomes ([11,2,3],) (a tuple containing the list you passed in).

Your function iterates through the value in that tuple, giving value=[11,2,3]. When you multiply a list by 10, you get a list 10 times longer.

like image 177
khelwood Avatar answered Jul 11 '26 20:07

khelwood