How to pass an array to a function in Python

Hello, Coders!! In this Python tutorial, we will learn how we can pass an array to a function in Python.

In Python, any type of data can be passed as an argument like string, list, array, dictionary, etc to a function. Numeric arrays are passed by reference when we pass them as an argument to the Python methods or functions.

Let’s understand the concept in more detail through an example program:

Program to pass an array to a function in Python

  • To create an array, import the array module to the program.
from array import *
  • Create an array of integer type having some elements.
arr = array('i', [86,87,88,89,90]) # here 'i' defines the datatype of the array as integer
  • Define a function display() that will take an array as an argument and display the elements of the array to the screen.
def display(a): # Here 'a' is an argument of type array
    for i in a:
        print(i)
  • Call the display() function by passing the previously created array as the argument.
display(arr)

 

Here is the complete program:

from array import *

def display(a): #here 'i' defines the datatype of the array as integer
    for i in a:
        print(i)
        
arr = array('i',[86,87,88,89,90]) # here 'i' defines the datatype of the array as integer
display(arr)

Output:

86
87
88
89
90

Hope this article has helped you to understand how we can pass an array to a function in a Python program easily.

You can also read, Python Array Module

Leave a Reply

Your email address will not be published. Required fields are marked *