Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass array as argument in python

Tags:

python

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?

like image 281
user12345 Avatar asked Apr 14 '16 10:04

user12345


1 Answers

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

like image 124
PM 2Ring Avatar answered Oct 05 '22 14:10

PM 2Ring