Arrays are often passed to functions so that multiple elements can be processed together instead of passing them one by one. A function can perform different operations on the array, such as traversing, searching, updating, or calculating values.
Using Python Array
Python's array module provides an array data structure that stores elements of the same data type. We can pass the entire array to a function just like any other object.
from array import array
def show(a):
for i in a:
print(i)
arr = array('i', [10, 20, 30, 40])
show(arr)
Output
10 20 30 40
Explanation: array is passed as a single argument to the show() function, which iterates through all its elements using a for loop.
Using Python List
Lists are commonly passed to functions in Python. Once passed, the function can access, modify, or perform any operation on the list elements.
def total(a):
print(sum(a))
lst = [5, 10, 15, 20]
total(lst)
Output
50
Explanation: list is passed directly to the function, where the built-in sum() function calculates the total of all elements.
Using Variable-Length Arguments (*args)
When the number of values is not known in advance, *args allows multiple arguments to be passed to a function. Inside the function, these values are available as a tuple.
def show(*a):
for i in a:
print(i)
show(10, 20, 30, 40)
Output
10 20 30 40
Explanation: values passed to show() are collected into a tuple using *args, allowing the function to process any number of arguments.
Using List Unpacking
If the data is already stored in a list, we can unpack the list while calling the function. Each element is passed as a separate argument.
def show(a, b, c):
print(a)
print(b)
print(c)
lst = [10, 20, 30]
show(*lst)
Output
10 20 30
Explanation: * operator unpacks the list, passing each element as an individual argument to the function. This is useful when the function expects a fixed number of parameters.