Arrays in Python are implemented using thearray module, which allows you to store elements of a specific type. You can pass an entire array to a function to perform various operations.
Syntax to create an array
array(data_type, value_list)
In this article, we'll explore how to pass arrays and lists to functions, with practical examples for both.
Example 1: Iterate Over an Array
We need to import an array, and after that, we will create an array with its datatype and elements, and then we will pass it to the function to iterate the elements in a list.
Pythonfromarrayimport*defshow(arr):foriinarr:print(i,end=', ')arr=array('i',[16,27,77,71,70,75,48,19,110])show(arr)
Output16, 27, 77, 71, 70, 75, 48, 19, 110,
Explanation:show() function receives an array and iterates over it using a for loop to print each element.
Example 2: Multiply All Elements of an Array
We need to import an array, and after that, we will create an array and pass it to a function to multiply the elements in a list.
Pythonfromarrayimport*defProduct(arr):p=1foriinarr:p*=iprint("Product: ",p)arr=array('f',[4.1,5.2,6.3])Product(arr)
OutputProduct: 134.31599601554856
Passing a List to a Function
The passing of parameters is not restricted to data types. This implies that variables of various data types can be passed in this procedure. So for instance, if we have thousands of values stored in a list and we want to manipulate those values in a specific function, we need to pass an entire list to the specific function.
Syntax to create a list:
var_name = [ele1, ele2, ...]
Let’s explore how to pass lists to functions in Python:
Example 1: Print All Elements of a List
Pythondefprint_animals(animals):forainanimals:print(a)ani=["Cat","Dog","Tiger","Giraffe","Wolf"]print_animals(ani)
OutputCatDogTigerGiraffeWolf
Explanation:print_animals() function takes a list animals and prints each animal using a for loop.
Example 2: Find the Product of All Numbers in a List
In a similar fashion let us perform another program where the list will be of type integers and we will be finding out the product of all the numbers present in the list.
PythondefProduct(nums):p=1foriinnums:p*=iprint("Product: ",p)l=[4,5,6]Product(l)
Example 3: Using *args to Pass a Variable Number of Arguments
Sometimes, the number of elements in a list isn’t fixed beforehand. In such cases, you can use *args to pass a variable number of arguments to a function.
PythondefProd(*arguments):p=1foriinarguments:p*=iprint("Product: ",p)Prod(4,5,1,2)
Explanation:*args collects all the arguments passed to the function into a tuple.