10

I am new to python. Now I need to declare the array of size 20 and pass the array to a function.

The function expecting the array is as:

function(*args)

The args is an input to the function().

Can anyone help me, how to pass array in python?

4
  • From which language are you coming from? Because this is as easy as function(array) Commented Apr 14, 2016 at 10:14
  • 4
    Possible duplicate of What does ** (double star) and * (star) do for Python parameters? Commented Apr 14, 2016 at 10:14
  • 1
    Beware that *args will unpack args. So function must accept at least len(args) arguments. Commented Apr 14, 2016 at 10:15
  • 1
    @DisplayName: That function signature can handle an arbitrary number of arguments, so to pass it a single list / tuple / array you can unpack it in the function call. Please see my answer for a simple demo. Commented Apr 14, 2016 at 10:57

2 Answers 2

20

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?.

Sign up to request clarification or add additional context in comments.

1 Comment

I should mention that bytes and bytearray are also array types, although (as the names indicate) they can only hold byte values. See docs.python.org/3/library/… for details.
-2

I think that what you need is easier than expected:

def arrayIn(arrayFunc):
    print(arrayFunc)

arraySize = 20
mineArray = [None]*arraySize
arrayIn(mineArray)

1 Comment

I suspect that the OP cannot change the signature of the function they're calling.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.