Functions

*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

python
1def add(*numbers):
2 total = 0
3
4 for num in numbers:
5 total += num
6
7 return total
8
9

Output:

text
16
2100

Here, numbers is a tuple:

python
1add(1, 2, 3)
2
3# numbers = (1, 2, 3)

Important

The name args is not mandatory. The * is what makes it work.

python
1def add(*numbers):
2 ...

2. *args with Regular Parameters

Regular parameters come before *args.

python
1def greet(greeting, *names):
2 for name in names:
3 print(greeting, name)
4
5greet("Hello", "Akash", "Rahul", "Amit")

Output:

text
1Hello Akash
2Hello Rahul
3Hello Amit

Here:

  • "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

python
1def user_info(**details):
2 print(details)
3
4user_info(name="Akash", age=25, city="Bangalore")

Output:

text
1{'name': 'Akash', 'age': 25, 'city': 'Bangalore'}

You can access individual values like a dictionary:

python
1def user_info(**details):
2 print(details["name"])
3 print(details["age"])
4
5user_info(name="Akash", age=25)

Output:

text
1Akash
225

4. *args vs **kwargs

*args**kwargs
AcceptsPositional argumentsKeyword arguments
Stored asTupleDictionary
Examplefunc(10, 20)func(a=10, b=20)

5. Using *args and `**kwargs Together

You can use both in the same function.

The order is:

text
1regular parameters → *args → **kwargs

Example

python
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:

text
1Name: Akash
2Skills: ('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.

python
1def add(a, b, c):
2 return a + b + c
3
4numbers = [10, 20, 30]
5
6print(add(*numbers))

This is equivalent to:

python
1add(10, 20, 30)

7. Unpacking with **

** can be used to unpack a dictionary into keyword arguments.

python
1def greet(name, age):
2 print(name, age)
3
4person = {
5 "name": "Akash",
6 "age": 25
7}
8
9greet(**person)

This is equivalent to:

python
1greet(name="Akash", age=25)

Quick Revision

text
1*args
2→ Multiple positional arguments
3→ Stored as tuple
4
5**kwargs
6→ Multiple keyword arguments
7→ Stored as dictionary
8
9* when calling
10→ Unpacks list/tuple
11
12** when calling
13→ Unpacks dictionary