Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Variable-length arguments in Python
You may need to process a function for more arguments than you specified while defining the function. These arguments are called variable-length arguments and are not named in the function definition, unlike required and default arguments.
Syntax
Syntax for a function with non-keyword variable arguments is this −
def functionname([formal_args,] *var_args_tuple):
"function_docstring"
function_suite
return [expression]
An asterisk (*) is placed before the variable name that holds the values of all nonkeyword variable arguments. This tuple remains empty if no additional arguments are specified during the function call.
Using *args for Variable Arguments
The following example demonstrates how to accept variable number of arguments using *args ?
# Function definition with variable arguments
def printinfo(arg1, *vartuple):
"""This prints a variable passed arguments"""
print("Output is:")
print(arg1)
for var in vartuple:
print(var)
# Now you can call printinfo function
printinfo(10)
print() # Add spacing between calls
printinfo(70, 60, 50)
Output is: 10 Output is: 70 60 50
Using **kwargs for Keyword Arguments
Python also supports variable-length keyword arguments using double asterisks (**kwargs) ?
def print_details(name, **kwargs):
"""Print name and additional details"""
print(f"Name: {name}")
for key, value in kwargs.items():
print(f"{key}: {value}")
# Call with keyword arguments
print_details("John", age=25, city="New York", job="Engineer")
Name: John age: 25 city: New York job: Engineer
Combining Both *args and **kwargs
You can use both *args and **kwargs in the same function definition ?
def flexible_function(required_arg, *args, **kwargs):
"""Function that accepts all types of arguments"""
print(f"Required argument: {required_arg}")
if args:
print("Additional positional arguments:")
for arg in args:
print(f" {arg}")
if kwargs:
print("Keyword arguments:")
for key, value in kwargs.items():
print(f" {key}: {value}")
# Test the function
flexible_function("Hello", 1, 2, 3, name="Alice", age=30)
Required argument: Hello Additional positional arguments: 1 2 3 Keyword arguments: name: Alice age: 30
Comparison
| Type | Syntax | Usage | Data Type |
|---|---|---|---|
| Variable positional | *args |
Multiple positional arguments | tuple |
| Variable keyword | **kwargs |
Multiple keyword arguments | dictionary |
| Combined | *args, **kwargs |
Both types together | tuple + dictionary |
Conclusion
Variable-length arguments provide flexibility in function definitions. Use *args for variable positional arguments and **kwargs for variable keyword arguments to create more versatile functions.
