In Python, a variable length argument, also known as varargs, allows a function to accept a variable number of arguments.
In Python, you can use the asterisk (*) symbol to denote a variable length argument parameter. This parameter collects all the arguments into a tuple or a list, depending on how it is defined. Let’s see an example:
def calculate_sum(*numbers):
total = 0
for num in numbers:
total += num
return total
result = calculate_sum(1, 2, 3, 4)
print(result) # Output: 10
Code language: Python (python)
In the example above, the calculate_sum
function accepts a variable number of arguments denoted by *numbers
. When the function is called with multiple arguments (1, 2, 3, 4), they are collected into the numbers
tuple inside the function. The function then iterates over the numbers
tuple and calculates the sum of all the values.
You can pass any number of arguments to the function, including zero arguments. If no arguments are passed, the numbers
tuple will be empty, and the sum will be 0.
Note that you can also use the double asterisk (**) to collect variable length keyword arguments into a dictionary. This allows you to pass arguments as key-value pairs. However, that is beyond the scope of your question regarding variable length arguments.
Read More;
- How to do Single Line for Loop in Python
- What is Len() in Python With Example
- What does V mean in Python?
- What is Async and Await in Python With Example
- For i in Range Python Example
- What is a decorator in Python With Example
- Can you do a for loop with a DataFrame in Python?
- What is Break Statement in Python With Example
- What is Name Error Value Error in Python?
- What is Inheritance With Examples in Python
- What is Token in Python With Example
- How to Use def in Python With Example