Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Introduction to Variable-length Arguments in Python
3.
Non - Keyword Arguments (args)
3.1.
Features of args
3.2.
Syntax of args
3.3.
Implementation
3.4.
python
4.
Keyworded Arguments (kwargs)
4.1.
Features of kwargs
4.2.
Syntax of kwargs
4.3.
Implementation
4.4.
python
5.
Difference Between Keyworded and Non-Keyworded Arguments
5.1.
Using args and kwargs to Call a Function
5.2.
python
5.3.
Unpacking Arguments with *args and **kwargs
5.4.
python
5.5.
python
5.6.
Comparing Variable Length Arguments versus Fixed Arguments
6.
Best Practices for Using Variable-Length Arguments
6.1.
python
6.2.
python
7.
Frequently Asked Questions
7.1.
How do you pass variable-length arguments in Python?
7.2.
What are the arguments in Python?
7.3.
Are there any disadvantages to using variable-length arguments in Python?
8.
Conclusion
Last Updated: Mar 27, 2024
Easy

Variable Length Arguments in Python

Author Kanak Rana
0 upvote
gp-icon
Basics of python
Free guided path
7 chapters
99+ problems
gp-badge
Earn badges and level up

Introduction

As a Python developer, you know that writing flexible and adaptable code is essential. But did you know that variable-length arguments can help you achieve that goal? 

In this article, we'll learn the concept of variable length arguments in Python, show you how to use them effectively, and provide some best practices to help you write clean and efficient code. This article will help you enhance your programming skills and improve your code's functionality.

Variable Length Arguments in Python

Let's start with variable length arguments in Python.

Introduction to Variable-length Arguments in Python

In Python, Variable-Length Arguments (or varargs) are a way to pass a variable number of arguments to a function. This means that you can pass any number of arguments to a function, and the function will handle them all.

Understanding Variable Length Arguments in Python


Python provides two ways to define a function with variable-length arguments:

  • Non-Keyworded Arguments
     
  • Keyworded Arguments
Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Non - Keyword Arguments (args)

In Python, non-keyworded arguments, also called positional arguments, are values passed to a function based on their position/order in the function call. In Python, you can define a function that accepts non-keyworded arguments using the asterisk " " syntax in the function definition. 

Features of args

  • The number of non-keyworded arguments is defined by *args, and we can perform operations on the tuple
     
  • It makes the function flexible

Syntax of args

The syntax for a method with non-keyword variable arguments is given below:

//declaring the function with various arguments
def functionname([formal_args,] *var_args_tuple ):
"function_docstring"
function_suite
return [expression]

 

An asterisk (*) is placed before the variable name that contains the contents of all non-keyword variable parameters. If no more parameters are specified during the function call, the tuple is empty.

Implementation

  • python

python

def sum_numbers(*args):
   result = 0
   for num in args:
       result += num
   return result

# take user input
numbers = input("Enter numbers separated by space: ")

# convert user input to integers
numbers_list = [int(num) for num in numbers.split()]

# call the sum_numbers function with user input
print(sum_numbers(*numbers_list))


Input:

3 5 4 6 2 1


Output:

output


Explanation:

The code defines a function called "sum_numbers" that accepts any number of arguments using the asterisk (*) syntax. It initializes a variable called "result" to 0 and then loops through all the arguments, adding each argument to the result variable. Finally, the function returns the value of the result variable.

In the main code block, the user is prompted to enter numbers separated by spaces. The input is then converted to a list of integers using list comprehension. The sum_numbers function is then called with the list of integers as arguments using the asterisk (*) syntax to unpack the list. Finally, the result of the function is printed to the console.

Keyworded Arguments (kwargs)

The **kwargs is used to pass a variable number of keyword arguments to a function. The term "kwargs" is short for "keyword arguments", which are arguments passed to a function using the syntax key=value. With **kwargs, you can pass any number of keyword arguments to a function, and the function will receive them as a dictionary. The keys in the dictionary will be the argument names, and the values will be the corresponding argument values.

Features of kwargs

  • **kwargs is in responsible for passing a variable number of keyword arguments dictionary to the method, allowing it to conduct dictionary operations
     
  • The double star gives it the name kwargs. The double star allows us to submit keyword arguments (in any number). When you pass a variable into a function as a keyword argument, you name it
     
  • The kwargs can be regarded as a dictionary that maps each word to the value we send along with it, which is why there doesn't appear to be any sequence in which the kwargs were printed out when we iterate over them

Syntax of kwargs

def functionname([formal_args,] **var_kwargs_dict):
    "function_docstring"
    function_suite
    return [expression]

 

This Python function syntax defines a function named functionname that accepts optional formal arguments, collects keyword arguments into a dictionary named var_kwargs_dict, has an optional docstring then contains the function code, and can return a value.

Implementation

  • python

python

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

user_input = input("Enter some key-value pairs (separated by commas):\n").strip()
key_value_pairs = [pair.strip().split("=") for pair in user_input.split(",")]
kwargs = {key.strip(): value.strip() for key, value in key_value_pairs}

print_kwargs(**kwargs)


Output:

output


Explanation:

In the above code, a function called print_kwargs takes an arbitrary number of keyword arguments. The function prints each key-value pair with the format "key = value" after it iterates through the keyword arguments using the kwargs.items() method.

In the second section of the code, the user is asked to enter a few key-value pairs separated by commas. The input is then divided into pairs, each divided by an equal sign. A dictionary comprehension turns the list of pairs that results into a dictionary called kwargs. The function print_kwargs is then invoked using the **kwargs syntax, which sends the key-value pairs from the kwargs dictionary to the function as keyword arguments. The function then uses the print statement defined in the first part of the code to print each key-value pair with the format "key = value."

The code takes key-value pair input from the user, creates a dictionary, and then uses the print_kwargs function to print the dictionary's key-value pair entries.

Note: 

The .split() method separates a string into a list of substrings based on a given delimiter. The delimiter is a default whitespace character such as a space, tab, or newline. However, you can specify a different delimiter by passing it as an argument to the method.

For managing varying numbers of keyword arguments, Python's **kwargs syntax is a strong tool. It gives functions more flexibility by allowing them to accept a variety of named parameters without having to define them specifically in the function signature.

Maintaining a consistent naming strategy for the keyword arguments when using the **kwargs syntax is essential to ensuring readability and maintainability in your code. The goal of the function and the anticipated inputs are simpler to grasp for both developers and users when the function's keywords are descriptive and meaningful.

The **kwargs feature improves code reuse. Your codebase can become more modular and versatile by using generic functions which can handle a wide variety of inputs. 

Difference Between Keyworded and Non-Keyworded Arguments

Keyworded Arguments

Non-Keyworded Arguments

Uses a double asterisk (**) before the parameter name.

Uses a single asterisk (*) before parameter name.

For a use case, arguments are optional or need to be passed when named.

The number of arguments is unknown or may vary for a use case.

Keyword arguments can make code more readable and self-explanatory, as the argument names can provide context for what the function is doing.

Non-keyword arguments can make code less readable and error-prone, as it can be difficult to remember which argument corresponds to which parameter.

Keyword arguments can make it easier to maintain code over time, as it is more explicit which arguments are being passed and what they represent.

Non-keyword arguments can make code harder to maintain, especially if the function signature changes over time and the argument positions must be updated throughout the codebase.

Accessed via a key-value pair in the dictionary using its name.

Accessed via a for loop or index to iterate through the tuple.

Arguments are passed as a dictionary.

Arguments are passed as a tuple.

Using args and kwargs to Call a Function

Python supports two methods for passing arguments when calling functions: positional and keyword arguments, also called args and kwargs. Keyword arguments are passed by explicitly stating the parameter name and value, as opposed to positional arguments, which are passed in the order they appear in the function definition.

Example:

  • python

python

def my_func2(*args, **kwargs):
print("Positional arguments:")
for arg in args:
print(arg)

print("Keyword arguments:")
for key, value in kwargs.items():
print(f"{key} = {value}")

# Enter the user to enter positional arguments
args_input = input("Enter positional arguments separated by commas: ")
args_list = args_input.split(",")

# Enter the user to enter keyword arguments
kwargs_input = input("Enter keyword arguments in the format key=value separated by commas: ")
kwargs_list = kwargs_input.split(",")
kwargs_dict = {}

# Parse the keyword arguments entered by the user
for kwarg in kwargs_list:
key, value = kwarg.split("=")
kwargs_dict[key] = value

# Call the function with the user input arguments
my_func2(*args_list, **kwargs_dict)


Explanation:

This code defines a function called my_func2 that accepts any number of positional and keyword arguments. It then prompts the user to enter the positional and keyword arguments as input strings, which are parsed and converted into lists and a dictionary. 

The my_func2 function is then called with the parsed user input arguments using the *args and **kwargs syntax to pass the positional and keyword arguments as separate arguments and a dictionary, respectively. 

The function then prints out the positional and keyword arguments passed to it, along with their values. This code allows for flexible and customizable function input with user-defined arguments.

Output:

Enter positional arguments separated by commas: dog,cat,rabbit
Enter keyword arguments in the format key=value separated by commas: sound=bark,color=brown
Positional arguments:
dog
cat
rabbit
Keyword arguments:
sound = bark
color = brown

Unpacking Arguments with *args and **kwargs

When we define a function in Python, we may not always know exactly how many arguments it will receive. This is where the concept of "packing" and "unpacking" comes in handy.

In Python, the *args syntax can pass a variable number of arguments to a function. The * before the variable name tells Python to pack all of the arguments into a tuple. This allows the function to work with any number of arguments passed to it.

Similarly, we can use **kwargs to pass a variable number of keyword arguments to a function. The ** before the variable name tells Python to pack all keyword arguments into a dictionary.

Unpacking works in the opposite direction. If we have a list or tuple of values we want to pass as arguments to a function, we can use the * syntax to unpack them. Similarly, if we have a dictionary of keyword arguments, we can use the ** syntax to unpack them.

Example:

For *args:

  • python

python

def find_max(*args):
max_value = max(args)
return max_value

numbers = input("Enter numbers separated by spaces: ")
numbers_list = [int(num) for num in numbers.split()]

max_number = find_max(*numbers_list)
print("The maximum number is:", max_number)


Output:

Output

For *kwargs:

  • python

python

def print_details(**kwargs):
for key, value in kwargs.items():
print(key + ": " + value)

name = input("Enter your name: ")
age = input("Enter your age: ")
email = input("Enter your email: ")

print_details(name=name, age=age, email=email)


Output:

Output

Comparing Variable Length Arguments versus Fixed Arguments

Variable Length Arguments

Fixed Arguments

A number of arguments

are variable.

A number of arguments are

fixed.

The orderThe order of arguments is arbitrary.

Order of arguments is fixed.

Useful when the number of inputs is not predetermined or when the type of inputs can vary.

Useful when the function requires a specific number of inputs and the type and order of the inputs are fixed.

print() function in Python that can take any number of arguments.

len() function in Python that takes only one argument, or math.pow() function in Python that takes two arguments in a specific order.

The choice between variable length and fixed arguments ultimately depends on the function's specific needs and the codebase's requirements. It's important to carefully consider these factors and choose the argument type that best meets those needs.

Best Practices for Using Variable-Length Arguments

While variable-length arguments can make your code more flexible and adaptable, using them wisely is important. Here are some best practices for using variable-length arguments in Python:

1. Use default values: If your function has optional arguments, it's a good idea to use default values to make it more user-friendly.

Code:

  • python

python

def my_function(arg1, arg2, *args, kwarg1="default1", kwarg2="default2", **kwargs):
print("arg1:", arg1)
print("arg2:", arg2)
print("args:", args)
print("kwarg1:", kwarg1)
print("kwarg2:", kwarg2)
print("kwargs:", kwargs)

my_function("value1", "value2", "extra1", "extra2", kwarg2="new_value2", kwarg3="value3", kwarg4="value4")


Output:

Output

Using defaults is important because it gives functions a sensible default behavior while allowing callers to override that behavior if necessary. This makes the functions more flexible and easier to use in different contexts. Using default values ​​can also make your code cleaner and easier to read because it avoids repeating code to set the default behavior.

2. Don't overuse variable-length arguments: While they can make your code more flexible, don't overuse them. If a function only needs a fixed number of arguments, using them instead of variable-length arguments is best.

3. Use type annotations: Type annotations can help improve the readability of your code and make it easier for others to understand what types of arguments are expected.

Code:

  • python

python

from typing import List, Dict

def process_data(*args: List[int], **kwargs: Dict[str, str]) -> List[str]:
# process the input data
processed_data = [str(x) for x in args]

# add any additional options specified in kwargs
for key, value in kwargs.items():
processed_data.append(f"{key}: {value}")

return processed_data


# example usage of process_data function
result = process_data(1, 2, 3, name=' Rakesh', age='22')
print(result)


Explanation:

Using type annotations, we can say that **kwargs is a variable-length dictionary of string keys and string values and *args is a variable-length list of integers in this example. Making it clear what kinds of arguments the function expects helps users of the function work more accurately and without confusion.

Type annotations allow us to improve code completion and error checking by utilizing tools like static type checkers and integrated development environments (IDEs) with type hinting support. This could enhance the quality of the code and speed up the development process.


Output:

Output

Frequently Asked Questions

How do you pass variable-length arguments in Python?

To pass variable-length arguments in Python, use an asterisk (*) before the argument name. *args is used for a variable number of positional arguments. For example: ”def my_function(*args):”

What are the arguments in Python?

In Python, an argument is a value or variable passed to a function or method when it is called. Arguments provide additional information to a function or method it needs to perform its task.

Are there any disadvantages to using variable-length arguments in Python?

One disadvantage of using variable length arguments in Python is that it can make code less readable and harder to maintain if used excessively. Additionally, it may not be clear what types of arguments are expected without looking at the function definition.

Conclusion

Variable length arguments in python are a powerful feature in Python that can make your code more flexible and adaptable. Using the *args and **kwargs syntax, you can create functions that accept an arbitrary number of keyword arguments. However, using variable-length arguments wisely and following best practices is important to ensure your code remains clean, efficient, and easy to understand.

Suppose you want to know more about variable-length arguments in Python and articles like this. In that case, refer to the following articles:
 

Refer to our guided paths on Coding Ninjas Studio to learn more about DSA, Competitive Programming, JavaScript, System Design, etc. Enrol in our courses and refer to the mock test and problems available. Take a look at the interview experiences and interview bundle for placement preparations.

Happy Learning!

Previous article
Is python Case sensitive when dealing with identifiers?
Next article
Static Variable in Python
Guided path
Free
gridgp-icon
Basics of python
7 chapters
127+ Problems
gp-badge
Earn badges and level up
Live masterclass