Skip to content

Variable length arguments in Python

  • by

In Python, you can use variable length arguments to define functions that can accept a variable number of arguments. This allows you to pass any number of arguments to the function without explicitly specifying their count.

There are two ways to define variable length arguments in Python: using the *args syntax and using the **kwargs syntax.

Using *args:

  • The *args syntax allows you to pass a variable number of non-keyword arguments to a function.
  • In the function definition, *args is used to collect all the positional arguments into a tuple.
def my_function(*args):
    for arg in args:
        print(arg)

my_function(1, 2, 3)  # 1 2 3
my_function('Hello', 'World')  # Hello World

Using **kwargs:

  • The **kwargs syntax allows you to pass a variable number of keyword arguments to a function.
  • In the function definition, **kwargs is used to collect all the keyword arguments into a dictionary, where the keys are the argument names and the values are the corresponding argument values.
def my_function(**kwargs):
    for key, value in kwargs.items():
        print(key, value)

my_function(name='Alice', age=25)  # name Alice, age 25
my_function(language='Python', version='3.9')  # language Python, version 3.9

Variable length arguments in Python example

You can also use a combination of *args and **kwargs in a single function to accept both positional and keyword arguments. In this case, the positional arguments are collected into args, and the keyword arguments are collected into kwargs.

def my_function(*args, **kwargs):
    for arg in args:
        print(arg)

    for key, value in kwargs.items():
        print(key, value)

my_function(1, 2, 3, name='Alice', age=25)

Output:

Variable length arguments in Python

Using variable length arguments can make your code more flexible and allow you to write functions that can handle different numbers of arguments.

Do comment if you have any doubts or suggestions on this Python function topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading