Back to Blog

Python *args and kwargs Explained - Beginner Tutorial #12 (with mini project)

Sandy LaneSandy Lane

Video: Python *args and kwargs Explained - Beginner Tutorial #12 (with mini project) by Taught by Celeste AI - AI Coding Coach

Watch full page →

Python *args and **kwargs Explained - Beginner Tutorial

In Python, *args and **kwargs allow you to write flexible functions that accept an arbitrary number of positional and keyword arguments. This tutorial covers how to collect extra arguments, combine them with regular parameters, and use unpacking to forward arguments between functions.

Code

# *args collects extra positional arguments into a tuple
def sum_all(*args):
  total = 0
  for num in args:
    total += num
  return total

# **kwargs collects extra keyword arguments into a dictionary
def print_info(**kwargs):
  for key, value in kwargs.items():
    print(f"  {key}: {value}")

# Combining *args and **kwargs with regular parameters
def log_event(event, *tags, **details):
  print(f"Event: {event}")
  print("Tags:")
  for tag in tags:
    print(f"  - {tag}")
  print("Details:")
  for key, value in details.items():
    print(f"  {key}: {value}")

# Unpacking a list and dictionary when calling functions
numbers = [1, 2, 3]
print("Sum:", sum_all(*numbers))  # Unpacks list into positional arguments

config = {'name': 'Alice', 'age': 30}
print_info(**config)  # Unpacks dictionary into keyword arguments

# Mini Project: Event Planner using flexible arguments
def event_planner(event_name, *participants, **event_details):
  print(f"Planning event: {event_name}")
  print("Participants:")
  for p in participants:
    print(f" - {p}")
  print("Event Details:")
  for key, value in event_details.items():
    print(f" {key}: {value}")

event_planner("Birthday Party", "Alice", "Bob", location="Park", time="5 PM")

Key Points

  • *args collects extra positional arguments into a tuple for flexible argument lists.
  • **kwargs collects extra keyword arguments into a dictionary for named parameters.
  • You can combine regular parameters with *args and **kwargs in one function definition.
  • Use * to unpack lists/tuples and ** to unpack dictionaries when calling functions.
  • Flexible arguments enable powerful patterns like forwarding arguments and building versatile APIs.