Skip to main content
Module 5 · Lesson 3 of 419/36 in the course~16 min
Module lessons (3/4)

*args and **kwargs

Lesson preview5 hands-on exercises readyPython Course · Module 5 — Functions

Variadic functions: *args collects positional arguments, **kwargs collects keywords, and call-site unpacking.

What you'll learn in this lesson

  • Accept an arbitrary number of positional arguments with *args (gathered into a tuple).
  • Accept flexible named arguments with **kwargs (collected in a dictionary).
  • Decompose sequences and dictionaries at the call-site with fn(*items, **options) and respect the strict order in the signature.

Overview

Often a function needs to be able to receive an arbitrary number of values (sum_all(1, 2) or sum_all(1, 2, 3, 4)) or pass unknown options to another function without knowing the details. Python solves both cases with the packing operators * and **.

In the definition (def fn(*args, **kwargs):), the asterisks collect the arguments scattered in a tuple (args) and a dict (kwargs). Conversely, in the call (fn(*seq, **mapping)), the same asterisks expand a list into positional arguments and a dict into chiave=valore pairs.

Sections covered in this lesson

  1. 1The mental model: packing into def vs exploding into the call
  2. 2Variadic functions *args and **kwargs
  3. 3Order in signature, unpacking in call and transparent wrappers
  4. 4Quick check
  5. 5Test yourself
Pro Lesson · Module 5 — Functions

Unlock "*args and **kwargs" and the full Python Course curriculum

Variadic functions: *args collects positional arguments, **kwargs collects keywords, and call-site unpacking.

Unlock all 5 hands-on exercises in this lesson plus every advanced WebAssembly module with automated checks.

  • Instant access to all advanced modules in Python Course plus 17 more courses
  • Hands-on browser exercises with automated test suites and solutions
  • 14-day money-back guarantee processed via Paddle.com

14-day guarantee · Cancel anytimeModule 1, all 18 interactive games, and cheatsheets are always free.