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?

1
  • 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. Commented Aug 22, 2018 at 9:59

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Got it, Thank you... Coming from the C++ background, I mistook *args with pointer-like functionality. Will learn tuples in python now.
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.