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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With