Lecture

Understanding and Using Variable-Length Arguments

Variable-length arguments, also known as varargs, are a feature in functions that allow you to pass an arbitrary number of arguments without having to predefine their number.

To use variable arguments in a function, prefix the parameter with * for positional arguments or** for keyword arguments.

* accepts an arbitrary number of positional arguments, whereas ** accepts an arbitrary number of keyword argument pairs.


*args Syntax

In Python, *args is used to pass a variable number of positional arguments to a function when the number of arguments isn't predetermined.

By prefixing the parameter with *, the function processes these arguments as a tuple internally.

Example of *args
def print_numbers(*numbers): for number in numbers: print(number) print_numbers(1, 2, 3) # Output: 1, 2, 3

**kwargs Syntax

**kwargs allows passing a variable number of keyword arguments to a function.

By prefixing the parameter with **, the function processes these arguments as a dictionary internally.

Example of **kwargs
def print_numbers(**numbers): for key, value in numbers.items(): print(f'{key}: {value}') print_numbers(first=1, second=2, third=3) # Output: first: 1, second: 2, third: 3
Quiz
0 / 1

Values passed with variable argument *args are treated as a dictionary within the function.

True
False

Lecture

AI Tutor

Design

Upload

Notes

Favorites

Help

Code Editor

Run
Generate

Execution Result