3

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?

asynts
  • 2,213
  • 2
  • 21
  • 35
Tesla
  • 87
  • 11
  • 3
    try doing `print(args)` and I think you'll see why. `args` in your case is `([11,2,3],)` -- a length 1 tuple of lists. – FHTMitchell Aug 22 '18 at 09:59

2 Answers2

6

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.

khelwood
  • 55,782
  • 14
  • 81
  • 108
  • Got it, Thank you... Coming from the C++ background, I mistook *args with pointer-like functionality. Will learn tuples in python now. – Tesla Aug 22 '18 at 10:48
0

Probably what are you looking for is expanding the list print_list(*_list) which pass each element of the input list as a function parameter and so the output is 110 20 30.

If you would have the list as numpy.array(_list) * 10 then the multiplications will also work.

Jirka
  • 1,126
  • 6
  • 25