Python pass list as argument

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 = 

Источник

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
Оцените статью