Flexiple Logo
  1. Home
  2. Blogs
  3. Python
  4. *args And **kwargs In Python

*args And **kwargs In Python

Author image

Harsh Pandey

Software Developer

Published on Wed Mar 13 2024

In Python, *args and **kwargs allow functions to accept a variable number of arguments. *args is used for positional arguments, passed as a tuple, while **kwargs handles keyword arguments, passed as a dictionary. This flexibility facilitates the creation of versatile functions that can adapt to a wide range of input parameters.

What Is Python *args?

Python *args is a mechanism in function definitions that allows you to pass a variable number of positional arguments. You use *args in the parameter list of a function to denote that the function can accept any number of positional arguments beyond those already named. The arguments passed to the function are accessible as a tuple within the function body.

For example, consider a function designed to sum any number of numbers.

def sum_numbers(*args):
    return sum(args)

print(sum_numbers(1, 2, 3))
print(sum_numbers(1, 2, 3, 4, 5))

Output:

6
15

In this code, sum_numbers can take any number of arguments, thanks to *args, and calculates their sum.

What Is Python **kwargs?

Python **kwargs is a parameter that allows a function to accept an arbitrary number of keyword arguments. These arguments are passed into the function as a dictionary, enabling dynamically handling named arguments.

For example, consider a function that needs to handle different attributes of a profile.

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

create_profile(name="John Doe", age=30, profession="Developer")

Output:

name: John Doe
age: 30
profession: Developer

In this code, **kwargs collects any number of named arguments passed to create_profile and prints out each key-value pair.

Using Both *args And **kwargs In Python To Call A Function

Using both *args and **kwargs in Python to call a function enables passing a variable number of arguments to a function. This flexibility makes your functions adaptable to various input scenarios.

def function_example(*args, **kwargs):
    print("Positional arguments:", args)
    print("Keyword arguments:", kwargs)

function_example(1, 2, 3, name='Alice', job='Engineer')

Output:

Positional arguments: (1, 2, 3)
Keyword arguments: {'name': 'Alice', 'job': 'Engineer'}

Using *args and **kwargs In Python To Set Values Of Object

Using *args and **kwargs in Python allows for flexible assignment of values to objects. This flexibility is beneficial in object-oriented programming when initializing object attributes.

For instance, *args can be used to pass multiple values to set up various attributes of an object in a single go. Consider a class Book where we want to assign attributes dynamically.

class Book:
    def __init__(self, *args):
        self.title, self.author, self.year = args

book = Book("The Great Gatsby", "F. Scott Fitzgerald", 1925)
print(book.title, book.author, book.year)

Output:

The Great Gatsby F. Scott Fitzgerald 1925

Similarly, **kwargs allows for keyword argument passing, offering a more readable way to initialize object attributes.

class Book:
    def __init__(self, **kwargs):
        self.title = kwargs.get('title')
        self.author = kwargs.get('author')
        self.year = kwargs.get('year')

book = Book(title="1984", author="George Orwell", year=1949)
print(book.title, book.author, book.year)

Output:

1984 George Orwell 1949

These approaches show how *args and **kwargs provide versatility in handling object attributes, making code more adaptable and readable.

Related Blogs

Browse Flexiple's talent pool

Explore our network of top tech talent. Find the perfect match for your dream team.