Varargs and keyword only parameters

Varargs and keyword only parameters

In Python, there are two types of function parameters: positional parameters and keyword parameters. Positional parameters are the most common type of parameter, and they are used to pass arguments to a function based on their position. Keyword parameters, on the other hand, are used to pass arguments to a function based on their name.

In addition to these types of parameters, Python also supports variable-length parameter lists and keyword-only parameters.

Variable-length parameter lists are specified using the *args syntax. When a function is defined with a parameter like *args, it can accept an arbitrary number of positional arguments. The arguments are collected into a tuple, which can be iterated over or passed to other functions.

For example, consider the following function that accepts a variable number of arguments and returns their sum:

sql

def sum(*args): result = 0 for arg in args: result += arg return result

In this function, the *args parameter collects any number of arguments passed to the function and stores them as a tuple. The for loop then iterates over the tuple and calculates its sum.

Keyword-only parameters, on the other hand, are specified using the * syntax. When a function is defined with a parameter like *, it can only accept keyword arguments that are not preceded by a positional argument. This means that the argument must be passed by name, and cannot be passed by position.

For example, consider the following function that accepts a keyword-only argument:

python

def greet(*, name): print(f”Hello, {name}!”) greet(name=”Alice”) # Output: Hello, Alice!

In this function, the * syntax indicates that the name parameter is a keyword-only parameter. This means that it can only be passed by name, and not by position. When the function is called, the name argument is passed by name, using the name=”Alice” syntax.

Apply for Python Certification!

https://www.vskills.in/certification/certified-python-developer

Back to Tutorials

Get industry recognized certification – Contact us

Menu