Pass an array to a function in Python

 So for instance, if we have thousands of values stored in an array and we want to perform the manipulation of those values in a specific function, that is when we need to pass an entire array to the specific function. 

Syntax: array(data_type, value_list)

Let us understand this with the help of a couple of examples

Example 1:

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. 

Python3




from array import *
 
def show(arr):
    for i in arr:
        print(i, end=', ')
 
arr = array('i', [16, 27, 77, 71, 70,
                  75, 48, 19, 110])
show(arr)


Output:

16, 27, 77, 71, 70, 75, 48, 19, 110

Time complexity: O(n), where n is the length of the input array.
Auxiliary space: O(1).

Example 2:

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.

Python3




from array import *
 
def Product(arr):
    p = 1
    for i in arr:
        p *= i
    print("Product: ", p)
 
arr = array('f', [4.1, 5.2, 6.3])
Product(arr)


Output:

Product:  134.31599601554856

Time complexity: O(n), where n is the length of the input array ‘arr’.
Auxiliary space: O(1), as only a single variable ‘p’ is used for computation and it does not depend on the size of the input.

How to pass an array to a function in Python

In this article, we will discuss how an array or list can be passed to a function as a parameter in Python

Similar Reads

Pass an array to a function in Python

So for instance, if we have thousands of values stored in an array and we want to perform the manipulation of those values in a specific function, that is when we need to pass an entire array to the specific function....

Pass a list to a function in Python

...

Contact Us