- Unpack and pass list, tuple, dict to function arguments in Python
- Unpack list and tuple with *
- With default arguments
- With variable-length arguments
- Unpack dict (dictionary) with **
- With default arguments
- With variable-length arguments
- Python Passing a List as an Argument
- Example
- Related Pages
- COLOR PICKER
- Report Error
- Thank You For Helping Us!
- Pass a List to a Function to act as Multiple Arguments
- Python List
- Pass a List to a Function as Multiple Arguments
- Example:
- Example:
- Conclusion
- Pass List to Function in Python
- Use a List and Pass It as an Argument to the Function
- Use the tuple() Function in Python
- Use the * Operator in Python
Unpack and pass list, tuple, dict to function arguments in Python
In Python, you can unpack list , tuple , and dict (dictionary) objects and pass their elements as function arguments by adding an asterisk * before a list or tuple, and two asterisks ** before a dictionary when calling the function.
For a basic understanding of Python functions, default arguments, and variable-length arguments using * and ** during function definition, refer to the following articles:
Unpack list and tuple with *
When specifying a list or tuple with * as an argument, it is unpacked, and each element is passed as a separate argument.
def func(arg1, arg2, arg3): print('arg1 =', arg1) print('arg2 =', arg2) print('arg3 =', arg3) l = ['one', 'two', 'three'] func(*l) # arg1 = one # arg2 = two # arg3 = three func(*['one', 'two', 'three']) # arg1 = one # arg2 = two # arg3 = three t = ('one', 'two', 'three') func(*t) # arg1 = one # arg2 = two # arg3 = three func(*('one', 'two', 'three')) # arg1 = one # arg2 = two # arg3 = three
The sample code uses lists, but the same applies to tuples.
If the number of elements does not match the number of arguments, a TypeError is raised.
# func(*['one', 'two']) # TypeError: func() missing 1 required positional argument: 'arg3' # func(*['one', 'two', 'three', 'four']) # TypeError: func() takes 3 positional arguments but 4 were given
With default arguments
If the function has default arguments, these defaults are used when there are not enough elements. If there are too many elements, a TypeError is raised.
def func_default(arg1=1, arg2=2, arg3=3): print('arg1 =', arg1) print('arg2 =', arg2) print('arg3 =', arg3) func_default(*['one', 'two']) # arg1 = one # arg2 = two # arg3 = 3 func_default(*['one']) # arg1 = one # arg2 = 2 # arg3 = 3 # func_default(*['one', 'two', 'three', 'four']) # TypeError: func_default() takes from 0 to 3 positional arguments but 4 were given
With variable-length arguments
If the function has a variable-length argument ( *args ), all elements following the positional argument are passed to the variable-length argument.
def func_args(arg1, *args): print('arg1 =', arg1) print('args =', args) func_args(*['one', 'two']) # arg1 = one # args = ('two',) func_args(*['one', 'two', 'three']) # arg1 = one # args = ('two', 'three') func_args(*['one', 'two', 'three', 'four']) # arg1 = one # args = ('two', 'three', 'four')
Unpack dict (dictionary) with **
By adding ** before a dict (dictionary) and specifying it as an argument, the keys and values are treated as argument names and their corresponding values. Each element is passed as a keyword argument.
def func(arg1, arg2, arg3): print('arg1 =', arg1) print('arg2 =', arg2) print('arg3 =', arg3) d = 'arg1': 'one', 'arg2': 'two', 'arg3': 'three'> func(**d) # arg1 = one # arg2 = two # arg3 = three func(**'arg1': 'one', 'arg2': 'two', 'arg3': 'three'>) # arg1 = one # arg2 = two # arg3 = three
If there are not enough keys or if the keys do not match the argument names, a TypeError is raised.
# func(**) # TypeError: func() missing 1 required positional argument: 'arg3' # func(**) # TypeError: func() got an unexpected keyword argument 'arg4'
With default arguments
If the function has default arguments, only the value of the argument name that matches the dictionary key is updated.
If a key does not match the argument name, a TypeError is raised.
def func_default(arg1=1, arg2=2, arg3=3): print('arg1 =', arg1) print('arg2 =', arg2) print('arg3 =', arg3) func_default(**'arg1': 'one'>) # arg1 = one # arg2 = 2 # arg3 = 3 func_default(**'arg2': 'two', 'arg3': 'three'>) # arg1 = 1 # arg2 = two # arg3 = three # func_default(**) # TypeError: func_default() got an unexpected keyword argument 'arg4'
With variable-length arguments
If the function has a variable-length argument ( **kwargs ), all elements with keys that do not match the argument name are passed to the variable-length argument.
def func_kwargs(arg1, **kwargs): print('arg1 =', arg1) print('kwargs =', kwargs) func_kwargs(**'arg1': 'one', 'arg2': 'two', 'arg3': 'three'>) # arg1 = one # kwargs = func_kwargs(**'arg1': 'one', 'arg2': 'two', 'arg3': 'three', 'arg4': 'four'>) # arg1 = one # kwargs = func_kwargs(**'arg1': 'one', 'arg3': 'three'>) # arg1 = one # kwargs =
Python Passing a List as an Argument
You can send any data types of argument to a function (string, number, list, dictionary etc.), and it will be treated as the same data type inside the function.
E.g. if you send a List as an argument, it will still be a List when it reaches the function:
Example
def my_function(food):
for x in food:
print(x)
fruits = [«apple», «banana», «cherry»]
Related Pages
COLOR PICKER
Report Error
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
Thank You For Helping Us!
Your message has been sent to W3Schools.
Top Tutorials
Top References
Top Examples
Get Certified
W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.
Pass a List to a Function to act as Multiple Arguments
In this article, we will learn how to pass a list to a function to act as multiple arguments in Python. We will understand the basic approach with some custom codes. Let’s first have a quick look over what is a list in Python.
Python List
Python has a built-in data type called list. It is like a collection of arrays with different methodology. Data inside the list can be of any type say, integer, string or a float value, or even a list type. The list uses comma-separated values within square brackets to store data. Lists can be defined using any variable name and then assigning different values to the list in a square bracket. The list is ordered, changeable, and allows duplicate values.
list1 = ["Ram", "Arun", "Kiran"] list2 = [16, 78, 32, 67] list3 = ["apple", "mango", 16, "cherry", 3.4]
Pass a List to a Function as Multiple Arguments
In Python, functions can take either no arguments, a single argument, or more than one argument. We can pass a string, integers, lists, tuples, a dictionary etc. as function arguments during a function call. The function accepts them in the same format and returns the desired output. Now, we want to pass a list that contains multiple elements and these elements act as multiple arguments of a function. This concept of passing a single list of elements as multiple arguments is known as Unpacking Argument List. We use *args to unpack the single argument into multiple arguments. We use the unpacking operator * when arguments are not available separately.
For example, range() function in Python stores three different arguments — start, stop, and step. If the user does not want to input the values separately, he can write the function call with the * operator to unpack the arguments out of a list or tuple.
Example:
In this example, my_list is iterable that is passed as an argument. Function definition treats this list as multiple arguments. Python program loops over the given list and uses each element of the list as a separate argument to the function. The below code just unpacks the list using the *args syntax when defining the function.
#function definition def add(*params): sum = 0 for num in params: sum += num print(sum) #input list my_list = [1,2,3] #function call add(*my_list)
Example:
This method is useful when the elements are not predetermined. We can pass multiple elements to a python function without predetermining the formal parameters. This example uses *args to avoid the code failing when the user does not know how many arguments will be sent to the function. You can use this method when elements in a list are not predetermined.
def calculateTotalSum(*arguments): totalSum = 0 for number in arguments: totalSum += number print(totalSum) # function call calculateTotalSum(5,4,3,2,1)
Conclusion
In this article, we used different examples to understand how can we unpack the list elements to use them as multiple arguments. We discussed *args syntax in Python to unpack the arguments of the list and use them separately in the function body.
Pass List to Function in Python
- Use a List and Pass It as an Argument to the Function
- Use the tuple() Function in Python
- Use the * Operator in Python
A list is one of the four fundamental data types that Python provides to store data. All these data types like lists, tuples, and dictionaries must sometimes be passed as an argument to a generic function.
This tutorial demonstrates the different ways to pass a list to a function in Python.
Use a List and Pass It as an Argument to the Function
Any argument passed on to the function is considered to be of the same data type inside the walls of the function. After being called inside the function, a list remains a list and does not change into any other data type.
The following code uses a list just like any other variable and directly passes it as an argument.
def tes1(cars): for i in cars: print(i) merc = ["GLA", "GLE", "GLS"] tes1(merc)
Use the tuple() Function in Python
This method implements modularity. The tuple() function splits all the elements of a list by converting the list to a tuple, and the elements are tackled as separate variables are passed as arguments to the function.
#Use tuple() function to split a list and pass it as an argument def argpass(a1, a2): print("Argument 1 : " + str(a1)) print("Argument 2 : " + str(a2)) lis1 = ["Merc", "BMW"] print("The original list is : " + str(lis1)) x, y = tuple(lis1) argpass(x, y)
The original list is : ['Merc', 'BMW'] Argument 1 : Merc Argument 2 : BMW
Use the * Operator in Python
The * operator is an easy and efficient method for implementing the current task at hand. The * operator can unpack the given list into separate elements that can later be tackled as individual variables and passed as an argument to the function.
def argpass(a1, a2): print("Argument 1 : " + str(a1)) print("Argument 2 : " + str(a2)) lis1 = ["merc", "bmw"] print("The original list is : " + str(lis1)) argpass(*lis1)
The original list is : ['merc', 'bmw'] Argument 1 : merc Argument 2 : bmw
Vaibhhav is an IT professional who has a strong-hold in Python programming and various projects under his belt. He has an eagerness to discover new things and is a quick learner.