Saturday, December 28, 2024
Google search engine
HomeLanguagesVariable Length Argument in Python

Variable Length Argument in Python

In this article, we will cover about Variable Length Arguments in Python. Variable-length arguments refer to a feature that allows a function to accept a variable number of arguments in Python. It is also known as the argument that can also accept an unlimited amount of data as input inside the function. There are two types in Python:

  • Non – Keyworded Arguments (*args)
  • Keyworded Arguments (**kwargs)

What is Python *args?

In Python, *args is used to pass a variable number of arguments to a function. It is used to pass a variable-length, non-keyworded argument list. These arguments are collected into a tuple within the function and allow us to work with them.

Feature of Python *args

  • To accept a variable number of arguments, use the symbol *; by convention, it is commonly used with the term args.
  • *args enables you to accept more arguments than the number of formal arguments you previously defined. With *args, you can add any number of extra arguments to your current formal parameters (including none).
  • Using the *, the variable that we associate with the * becomes iterable meaning you can do things like iterate over it, run some higher-order functions such as map and filter, etc.

In this example, we define a function sum_all that accepts any number of arguments. The *args syntax collects all the arguments into a tuple named args. Inside the function, we iterate through the args tuple and calculate the sum of all the numbers passed to the function.

Python3




def sum_all(*args):
    result = 0
    for num in args:
        result += num
    return result
 
print(sum_all(1, 2, 3, 4, 5))


Output

15


What is Python **kwargs?

In Python, **kwargs is used to pass a keyworded, variable-length argument list. We call kwargs with a double star. The reason for this is that the double star allows us to pass over keyword arguments (in any order). Arguments are collected into a dictionary within the function that allow us to access them by their keys.

Feature of Python **kwargs

  • A keyword argument is when you give the variable a name as you provide it into the function.
  • Consider the kwargs to be a dictionary that maps each keyword to the value we pass beside it. As a result, when we iterate through the kwargs, there appears to be no sequence in which they were printed.

In this example, the display_info function accepts a variable number of keyword arguments. Inside the function, we iterate through the kwargs dictionary and print out each key-value pair.

Python3




def display_info(**kwargs):
    for key, value in kwargs.items():
        print(f"{key}: {value}")
 
display_info(name="Alice", age=30, city="New York")


Output

name: Alice
age: 30
city: New York


Combining *args and **kwargs

You can also use both *args and **kwargs in the same function definition, allowing you to accept a mix of positional and keyword arguments.

Python3




def print_args_and_kwargs(*args, **kwargs):
    print("Positional arguments:")
    for arg in args:
        print(arg)
     
    print("Keyword arguments:")
    for key, value in kwargs.items():
        print(f"{key}: {value}")
 
print_args_and_kwargs(1, 2, 3, name="Alice", age=30)


Output

Positional arguments:
1
2
3
Keyword arguments:
name: Alice
age: 30


Unpacking Arguments with *args and **kwargs

In this example, we have a function called print_coordinates that takes four arguments (x, y, z, and w). We then create a list called coordinates containing four values. Using the *coordinates syntax, we unpack the values from the coordinates list and pass them as arguments to the print_coordinates function. The function then prints the values in a formatted way.

Python3




# Define a function with four arguments
def print_coordinates(x, y, z, w):
    print(f"X: {x}, Y: {y}, Z: {z}, W: {w}")
 
# Create a list of coordinates
coordinates = [1, 2, 3, 4]
 
# Unpack the list into four arguments for the function
print_coordinates(*coordinates)


Output

X: 1, Y: 2, Z: 3, W: 4


Similarly, In this we have a function print_values that takes four arguments (a, b, c, and d). We create a dictionary called arguments with values corresponding to these arguments, and then we call the function using the dictionary unpacking (**arguments) to pass the values to the function.

Python3




# Define a function with 4 arguments and print their values
def print_values(a, b, c, d):
    print(a, b, c, d)
 
# Create a dictionary with values for the function arguments
arguments = {'a': 10, 'b': 20, 'c': 30, 'd': 40}
 
# Call the function and unpack the dictionary
print_values(**arguments)


Output

10 20 30 40


Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments