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.
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.
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
Lessons in this chapter · Functions: Code Blocks for Specific Tasks
- 1. Creating Reusable Code Blocks with Functions
- 2. The Difference Between Parameters and Arguments
- 3. Handling TypeError for Function Parameters
- 4. Multiple-choice quiz
- 5. Understanding and Using Variable-Length Arguments
- 6. How to Assign Default Values to Function Parameters
- 7. Using Keyword Arguments
- 8. Various Function Return Methods
- 9. Coding Quiz - Output Formatting
- 10. Multiple-choice quiz
- 11. Fill-in-the-blank quiz
Values passed with variable argument *args are treated as a dictionary within the function.
Lecture
AI Tutor
Design
Upload
Notes
Favorites
Help