- 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
- Python Passing a List as an Argument
- Example
- Related Pages
- COLOR PICKER
- Report Error
- Thank You For Helping Us!
- 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
- Pass a List to a Function in Python
- Pass a List to a Function in Python
- Pass a List to a Python Function Just Like Any Other Data Type
- Difference Between Passing and Unpacking a List in Python
- Conclusion
- Related Article — Python Function
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.
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 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.
Pass a List to a Function in Python
- Pass a List to a Function in Python
- Pass a List to a Python Function Just Like Any Other Data Type
- Difference Between Passing and Unpacking a List in Python
- Conclusion
In Python, sending a list to a function is just like passing any other form of data. Let’s explore a little more into this subject.
Pass a List to a Function in Python
We will define a function testing with a single parameter, flavor . Then, we pass an argument named Cherry while calling the function.
This argument goes to the parameter variable flavor , which the function can then use. See the example below.
def testing(flavor): print("You chose:", flavor) testing("Cherry")
Pass a List to a Python Function Just Like Any Other Data Type
Python lists are like any other Python object that we can pass into a function as a simple variable. We have a function enjoy with a hobbies parameter in the code sample below.
Outside the function block, we define a list hobbies_list . While calling the function enjoy , we pass this variable, hobbies_list , as an argument.
This list goes to the parameter variable hobbies , and thus, the function can use the value of this list.
def enjoy(hobbies): #or def enjoy(hobbies=[]): for hobby in hobbies: print(hobby) hobbies_list = ['art', 'dance', 'sing'] enjoy(hobbies_list)
See how the enjoy function gets the value of the list, and the for loop inside it prints all the list items. Sometimes, you will also see the assignment of square brackets [] to the parameter variable while passing a list to a function.
Difference Between Passing and Unpacking a List in Python
In Python, we can use *args to pass a variable number of arguments to a function. Now, since a list has multiple values, people tend to use *args as the parameter variable for a list argument so that all the values of the list are taken care of.
When we define *args as the parameter variable, we signal the function to wait for a variable number of arguments. Passing the elements of a list as multiple arguments is similar to unpacking a list.
def subjects(*args): for subject in args: print("The subject name is ",subject) names = ['mathematics', 'science', 'history'] subjects(names)
The subject name is ['mathematics', 'science', 'history']
You will see the difference better if you compare this output with the below code.
def subjects(args): for subject in args: print("The subject name is ", subject) names = ['mathematics', 'science', 'history'] subjects(names)
The subject name is mathematics The subject name is science The subject name is history
Notice how the output changes based on *args . If *args is used to pass a list to a Python function, we might not get the expected results.
As a result, it’s important to select the appropriate syntax based on the requirements.
Conclusion
In this article, we learned about passing a list to a function in Python. We saw how we could pass a list to a function in Python just like we pass any other data type.
We further understood the difference between passing and unpacking lists as multiple arguments.
Related Article — Python Function
Copyright © 2023. All right reserved