*args, **kwargs
Python *args and **kwargs
Sometimes we don't know how many arguments will be passed to a function.
Python provides:
*args→ accepts multiple positional arguments**kwargs→ accepts multiple keyword arguments
1. *args
*args allows a function to accept any number of positional arguments.
The arguments are stored as a tuple inside the function.
Example
1def add(*numbers):2 total = 03 4 for num in numbers:5 total += num6 7 return total8 9
Output:
162100Here, numbers is a tuple:
1add(1, 2, 3)2 3# numbers = (1, 2, 3)Important
The name args is not mandatory. The * is what makes it work.
1def add(*numbers):2 ...2. *args with Regular Parameters
Regular parameters come before *args.
1def greet(greeting, *names):2 for name in names:3 print(greeting, name)4 5greet("Hello", "Akash", "Rahul", "Amit")Output:
1Hello Akash2Hello Rahul3Hello AmitHere:
"Hello"→greeting- Remaining arguments →
names
3. **kwargs
**kwargs allows a function to accept any number of keyword arguments.
The arguments are stored as a dictionary.
Example
1def user_info(**details):2 print(details)3 4user_info(name="Akash", age=25, city="Bangalore")Output:
1{'name': 'Akash', 'age': 25, 'city': 'Bangalore'}You can access individual values like a dictionary:
1def user_info(**details):2 print(details["name"])3 print(details["age"])4 5user_info(name="Akash", age=25)Output:
1Akash2254. *args vs **kwargs
*args | **kwargs | |
|---|---|---|
| Accepts | Positional arguments | Keyword arguments |
| Stored as | Tuple | Dictionary |
| Example | func(10, 20) | func(a=10, b=20) |
5. Using *args and `**kwargs Together
You can use both in the same function.
The order is:
1regular parameters → *args → **kwargsExample
1def user_info(name, *skills, **details):2 print("Name:", name)3 print("Skills:", skills)4 print("Details:", details)5 6user_info(7 "Akash",8 "Python",9 "SQL",10 age=25,11 city="Bangalore"12)Output:
1Name: Akash2Skills: ('Python', 'SQL')3Details: {'age': 25, 'city': 'Bangalore'}6. Unpacking with *
* can also be used when calling a function to unpack a list or tuple into separate arguments.
1def add(a, b, c):2 return a + b + c3 4numbers = [10, 20, 30]5 6print(add(*numbers))This is equivalent to:
1add(10, 20, 30)7. Unpacking with **
** can be used to unpack a dictionary into keyword arguments.
1def greet(name, age):2 print(name, age)3 4person = {5 "name": "Akash",6 "age": 257}8 9greet(**person)This is equivalent to:
1greet(name="Akash", age=25)Quick Revision
1*args2→ Multiple positional arguments3→ Stored as tuple4 5**kwargs6→ Multiple keyword arguments7→ Stored as dictionary8 9* when calling10→ Unpacks list/tuple11 12** when calling13→ Unpacks dictionary