Unpacking with * and **: How to Call Functions with Lists and Dictionaries

3D illustration of crates bursting open to release individual items into a function funnel, representing Python argument unpacking.

You’ve learned how to define a function that accepts *args and **kwargs. Now, we’ll learn the opposite: how to call a function using * and **. Understanding Python Unpacking args kwargs is essential for this process.

1. Unpacking Lists with *

Imagine you have a function and a list with the exact arguments it needs.

def add(a, b, c):
    return a + b + c

my_list = [10, 20, 30]

# The "long way"
add(my_list[0], my_list[1], my_list[2]) # 60

# The "unpacking" way
add(*my_list) # 60

The * operator says: “Explode this list and feed its items as individual arguments to the function.”

2. Unpacking Dictionaries with **

This is even more powerful. It matches dictionary keys to the function’s parameter names.

def greet(name, job, age):
    print(f"Hello {name}, you are a {age}-year-old {job}.")

my_dict = {
    "name": "Alice",
    "age": 30,
    "job": "Engineer"
}

# The "unpacking" way
greet(**my_dict)
# Output: Hello Alice, you are a 30-year-old Engineer.

This is extremely useful when working with APIs, where you get a JSON/dictionary of data and want to pass it directly to a class or function.

Similar Posts

Leave a Reply