What Is Variable Length Argument In Python With Example?

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;

  • Dmytro Iliushko

    I am a middle python software engineer with a bachelor's degree in Software Engineering from Kharkiv National Aerospace University. My expertise lies in Python, Django, Flask, Docker, REST API, Odoo development, relational databases, and web development. I am passionate about creating efficient and scalable software solutions that drive innovation in the industry.

    View all posts

Leave a Comment