![]() |
In this article, we will cover about Variable Length Arguments in Python. Variable-length arguments refer to a feature that allows a function to accept a variable number of arguments in Python. It is also known as the argument that can also accept an unlimited amount of data as input inside the function. There are two types in Python:
What is Python *args?In Python, *args is used to pass a variable number of arguments to a function. It is used to pass a variable-length, non-keyworded argument list. These arguments are collected into a tuple within the function and allow us to work with them. Feature of Python *args
In this example, we define a function sum_all that accepts any number of arguments. The *args syntax collects all the arguments into a tuple named args. Inside the function, we iterate through the args tuple and calculate the sum of all the numbers passed to the function. Python3
Output
15 What is Python **kwargs?In Python, **kwargs is used to pass a keyworded, variable-length argument list. We call kwargs with a double star. The reason for this is that the double star allows us to pass over keyword arguments (in any order). Arguments are collected into a dictionary within the function that allow us to access them by their keys. Feature of Python **kwargs
In this example, the display_info function accepts a variable number of keyword arguments. Inside the function, we iterate through the kwargs dictionary and print out each key-value pair. Python3
Output
name: Alice age: 30 city: New York Combining *args and **kwargsYou can also use both *args and **kwargs in the same function definition, allowing you to accept a mix of positional and keyword arguments. Python3
Output
Positional arguments: 1 2 3 Keyword arguments: name: Alice age: 30 Unpacking Arguments with *args and **kwargsIn this example, we have a function called print_coordinates that takes four arguments (x, y, z, and w). We then create a list called coordinates containing four values. Using the *coordinates syntax, we unpack the values from the coordinates list and pass them as arguments to the print_coordinates function. The function then prints the values in a formatted way. Python3
Output
X: 1, Y: 2, Z: 3, W: 4 Similarly, In this we have a function print_values that takes four arguments (a, b, c, and d). We create a dictionary called arguments with values corresponding to these arguments, and then we call the function using the dictionary unpacking (**arguments) to pass the values to the function. Python3
Output
10 20 30 40 |
Reffered: https://www.geeksforgeeks.org
Geeks Premier League |
Related |
---|
![]() |
![]() |
![]() |
![]() |
![]() |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 12 |