Pass List to Function in Python

Pass List to Function in Python

  1. Use a List and Pass It as an Argument to the Function
  2. Use the tuple() Function in Python
  3. 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.

Code:

def tes1(cars):
  for i in cars:
    print(i)
merc = ["GLA", "GLE", "GLS"]
tes1(merc)

Output:

GLA
GLE
GLS

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.

Code:

#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)

Output:

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.

Code:

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)

Output:

The original list is : ['merc', 'bmw']
Argument 1 : merc
Argument 2 : bmw