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
What does ** (double star) and * (star) do for parameters in Python?
While creating a function, the single asterisk (*) is used to accept any number of positional arguments, and the double asterisk (**) is used to accept any number of keyword arguments. These operators provide flexibility when you don't know in advance how many arguments will be passed to your function.
Using * (Single Asterisk) for Positional Arguments
The single asterisk (*) collects extra positional arguments into a tuple. By convention, this parameter is named *args.
Example
Create a function that accepts an arbitrary number of positional arguments ?
def sum_numbers(*args):
result = 0
for number in args:
result += number
return result
print(sum_numbers(1, 2, 3, 4, 5, 6, 7))
print(sum_numbers(10, 10, 10))
print(sum_numbers(1))
print(sum_numbers()) # No arguments
28 30 1 0
Using ** (Double Asterisk) for Keyword Arguments
The double asterisk (**) collects extra keyword arguments into a dictionary. By convention, this parameter is named **kwargs.
Example
Create a function that accepts an arbitrary number of keyword arguments ?
def sum_values(**kwargs):
result = 0
for key, value in kwargs.items():
print(f"{key}: {value}")
result += value
return result
print("Total:", sum_values(a=1, b=2, c=3, d=4))
print("Total:", sum_values(x=10, y=100))
a: 1 b: 2 c: 3 d: 4 Total: 10 x: 10 y: 100 Total: 110
Combining Both *args and **kwargs
You can use both operators in the same function. The order must be: regular parameters, *args, then **kwargs.
Example
def flexible_function(name, *args, **kwargs):
print(f"Name: {name}")
print(f"Args: {args}")
print(f"Kwargs: {kwargs}")
flexible_function("Alice", 1, 2, 3, age=25, city="New York")
Name: Alice
Args: (1, 2, 3)
Kwargs: {'age': 25, 'city': 'New York'}
Unpacking with * and ** Operators
These operators can also unpack collections when calling functions ?
Unpacking Lists and Tuples with *
def greet(first, second, third):
print(f"Hello {first}, {second}, and {third}!")
names = ["Alice", "Bob", "Charlie"]
greet(*names)
# Also works with tuples
name_tuple = ("David", "Eve", "Frank")
greet(*name_tuple)
Hello Alice, Bob, and Charlie! Hello David, Eve, and Frank!
Unpacking Dictionaries with **
def calculate(a, b, operation="add"):
if operation == "add":
return a + b
elif operation == "multiply":
return a * b
params = {'a': 10, 'b': 5, 'operation': 'multiply'}
result = calculate(**params)
print(f"Result: {result}")
Result: 50
Common Use Cases
| Operator | In Function Definition | In Function Call | Purpose |
|---|---|---|---|
* |
Collect positional args | Unpack sequences | Handle variable arguments |
** |
Collect keyword args | Unpack dictionaries | Handle variable keyword arguments |
Conclusion
The *args and **kwargs operators provide powerful flexibility in Python functions. Use *args for variable positional arguments and **kwargs for variable keyword arguments. They're essential for creating flexible APIs and wrapper functions.
