When you say "array" I assume you mean a Python list
, since that's often used in Python when an array would be used in other languages. Python actually has several array types: list
, tuple
, and array
; the popular 3rd-party module Numpy also supplies an array type.
To pass a single list (or other array-like container) to a function that's defined with a single *args
parameter you need to use the *
operator to unpack the list in the function call.
Here's an example that runs on Python 2 or Python 3. I've made a list of length 5 to keep the output short.
def function(*args):
print(args)
for u in args:
print(u)
#Create a list of 5 elements
a = list(range(5))
print(a)
function(*a)
output
[0, 1, 2, 3, 4]
(0, 1, 2, 3, 4)
0
1
2
3
4
Note that when function
prints args
the output is shown in parentheses ()
, not brackets []
. That's because the brackets denote a list, the parentheses denote a tuple. The *a
in the call to function
unpacks the a
list into separate arguments, but the *arg
in the function
definition re-packs them into a tuple.
For more info on these uses of *
please see Arbitrary Argument Lists and Unpacking Argument Lists in the Python tutorial. Also see What does ** (double star) and * (star) do for Python parameters?.