8. Star args
*args lets a function accept any number of positional arguments. The * before the parameter name collects them into a tuple:
- Inside the function,
numbersis a tuple:total(1, 2, 3)makes it(1, 2, 3). - The function can be called with zero, one or many arguments.
- The name
argsis a convention; the*is what matters. - Regular parameters can come before
*args:def f(first, *rest):.
Coming from JavaScript? *args looks like rest parameters (...args), but inside the function it is a tuple, not an array.
Sum any number of arguments
Define total(*numbers) that adds every number in numbers with a for loop and returns the sum. Print total(1, 2, 3).
Print exactly:
Create a free account to save your progress and unlock chapter 2.
Call it with more arguments
Define total(*numbers) as above. Print total(10, 20, 30, 40). The same function accepts a different number of arguments.
Print exactly:
Create a free account to save your progress and unlock chapter 2.
Count the arguments
Inside the function, *items is a tuple, so len(items) is the number of arguments. Define count_args(*items) that returns len(items). Print count_args("a", "b", "c").
Print exactly:
Create a free account to save your progress and unlock chapter 2.
Join the arguments
Define join_words(*words) that returns the words joined by a space, using " ".join(words). Print join_words("hello", "world").
Print exactly:
Create a free account to save your progress and unlock chapter 2.