0
0
PythonHow-ToBeginner · 3 min read

How to Unpack Function Arguments in Python: Simple Guide

In Python, you can unpack function arguments using *args for a list or tuple of positional arguments and **kwargs for a dictionary of keyword arguments. Use * to unpack iterables and ** to unpack dictionaries when calling functions.
📐

Syntax

To unpack arguments in Python functions, use *args to accept multiple positional arguments as a tuple, and **kwargs to accept multiple keyword arguments as a dictionary.

When calling a function, use * before an iterable to unpack positional arguments, and ** before a dictionary to unpack keyword arguments.

python
def func(*args, **kwargs):
    print('Positional args:', args)
    print('Keyword args:', kwargs)

# Calling with unpacking
args = (1, 2, 3)
kwargs = {'a': 4, 'b': 5}
func(*args, **kwargs)
Output
Positional args: (1, 2, 3) Keyword args: {'a': 4, 'b': 5}
💻

Example

This example shows how to define a function that accepts any number of positional and keyword arguments, and how to call it by unpacking a list and a dictionary.

python
def greet(*names, **options):
    greeting = options.get('greeting', 'Hello')
    for name in names:
        print(f"{greeting}, {name}!")

names_list = ['Alice', 'Bob']
options_dict = {'greeting': 'Hi'}
greet(*names_list, **options_dict)
Output
Hi, Alice! Hi, Bob!
⚠️

Common Pitfalls

One common mistake is forgetting to use * or ** when unpacking arguments, which causes the function to receive a single iterable or dictionary instead of separate arguments.

Another pitfall is mixing positional and keyword unpacking incorrectly, or using unpacking in the wrong order.

python
def add(x, y):
    return x + y

nums = (2, 3)

# Wrong: passing tuple as single argument
# add(nums)  # TypeError

# Right: unpack tuple into two arguments
result = add(*nums)
print(result)
Output
5
📊

Quick Reference

  • *args: collects extra positional arguments as a tuple.
  • **kwargs: collects extra keyword arguments as a dictionary.
  • Use * to unpack lists or tuples when calling functions.
  • Use ** to unpack dictionaries when calling functions.
  • Order when defining function parameters: regular, *args, default parameters, **kwargs.

Key Takeaways

Use *args to unpack positional arguments and **kwargs to unpack keyword arguments in function definitions.
Use * before a list or tuple and ** before a dictionary to unpack arguments when calling functions.
Forgetting * or ** when unpacking causes errors or unexpected behavior.
Order matters: positional arguments first, then *args, then keyword arguments, then **kwargs.
Unpacking helps write flexible functions that accept varying numbers of arguments.