↓ Skip to main content
Python

Python: Multi-Args

·2 mins

In Python, you can define a function with a variable number of arguments using the * and ** syntax in the function definition.

A single asterisk * in the function definition is used to capture positional arguments passed to the function as a tuple.

Here’s an example:

def foo(*args):
    for arg in args:
        print(arg)

foo(1, 2, 3)
# Output:
# 1
# 2
# 3

In this example, foo is defined to accept a variable number of positional arguments. The single asterisk * in the function definition def foo(*args) tells Python to capture any positional arguments passed to the function as a tuple args. When you call foo(1, 2, 3), the arguments 1, 2, and 3 are captured as a tuple (1, 2, 3) and passed to the function as args.

Double asterisks ** in the function definition are used to capture keyword arguments passed to the function as a dictionary.

Here’s an example:

def bar(**kwargs):
    for key, value in kwargs.items():
        print(f"{key}: {value}")

bar(a=1, b=2, c=3)
# Output:
# a: 1
# b: 2
# c: 3

In the example above, bar is defined to accept a variable number of keyword arguments.

The double asterisks ** in the function definition

def bar(**kwargs)

tells Python to capture any keyword arguments passed to the function as a dictionary kwargs. When you call bar(a=1, b=2, c=3), the keyword arguments a=1, b=2, and c=3 are captured as a dictionary {'a': 1, 'b': 2, 'c': 3} and passed to the function as kwargs.

Author
Samarthya
Engineer, learner, tinkerer. This is my trophy shelf of everyday work and leisure.

Related

Python: Class

·1 min
Learning to write Python code? A Python class is a blueprint for creating objects. It defines a set of attributes and methods that can be used to manipulate those attributes. Here’s an example of a simple Python class:

Python: Decorators

·1 min
Let’s learn about decorators @iamdecorator Decorators are used to modify or extend the behavior of functions and classes. They are useful for wrapping a function or class with additional functionality, such as logging, access control, performance measurement, or adding attributes. This can reduce code duplication, increase readability and maintainability.

Python: Inheritance

·2 mins
Inheritance is a mechanism in object-oriented programming (OOP) that allows you to create new classes that are derived from existing classes. The derived class inherits attributes and behaviors from the base class, and can also have additional attributes and behaviors of its own.