CodingNic

Intermediate Python

Args and Kwargs

Intermediate Python 34 min read

Args and Kwargs

Args and Kwargs

Sometimes you do not know how many values a function will receive.

Python gives two tools for flexible functions:

  • *args
  • **kwargs

What Is *args?

*args collects extra positional arguments into a tuple.

Positional arguments are values passed by position.

Basic Example

python
def add_all(*args):
    print(args)

add_all(1, 2, 3)

Output

text
(1, 2, 3)

Sum Example

python
def add_all(*args):
    total = 0

    for num in args:
        total += num

    print(total)

add_all(5, 10, 15)

Output

text
30

What Is **kwargs?

**kwargs collects extra keyword arguments into a dictionary.

Keyword arguments use names.

Basic Example

python
def show_info(**kwargs):
    print(kwargs)

show_info(name="Tom", age=25)

Output

text
{'name': 'Tom', 'age': 25}

Loop Through kwargs

python
def show_info(**kwargs):
    for key, value in kwargs.items():
        print(key, value)

show_info(name="Sara", city="Toronto")

Output

text
name Sara
city Toronto

Use Both Together

python
def demo(*args, **kwargs):
    print(args)
    print(kwargs)

demo(1, 2, name="Tom", score=90)

Output

text
(1, 2)
{'name': 'Tom', 'score': 90}

Why These Matter

They help you build:

  • flexible functions
  • reusable tools
  • wrappers
  • decorators
  • configuration functions

Naming Note

You can use other names, but args and kwargs are the common style.

Example:

python
def test(*numbers, **data):
    pass

Code Along

Create a function that multiplies all numbers using *args.

Mini Challenge

Create a function:

python
profile(*args, **kwargs)

Tasks:

  • Print all values in args
  • Print all keys and values in kwargs

Run:

python
profile("Admin", "Active", name="Maya", country="Canada")

Expected output:

text
Admin
Active
name Maya
country Canada

Real World Use Case

Frameworks and libraries use *args and **kwargs for flexible APIs, decorators, and configuration.

Quiz

  1. What does *args collect?
  2. What does **kwargs collect?
  3. Is args a list or tuple?
  4. Why are these useful?

Assignment

Create a function that prints the largest number from any amount of *args.

Summary

You learned how *args and **kwargs make functions flexible by accepting many values.