How to pass an array to a function in Python

Published on Aug. 22, 2023, 12:15 p.m.

In Python, you can pass an array (or any iterable) to a function as an argument. Here is an example of how this can be done:

def my_function(arr):
    for i in arr:
        print(i)

my_array = [1, 2, 3, 4, 5]
my_function(my_array)

In this example, we define a function called my_function that accepts an array as an argument and prints each element in the array. We then create an array called my_array and pass it to the my_function as an argument.

Note that Python lists are commonly used as arrays in Python, as they are dynamic and can change size. However, you can also use the array module to create arrays of specific type codes (e.g. 'i' for integers).

Tags: