I am a complete newbie to python and attempting to pass an array as an argument to a python function that declares a list/array as the parameter.
I am sure I am declaring it wrong,
here goes:
def dosomething(listparam):
#do something here
dosomething(listargument)
Clearly this is not working, what am I doing wrong?
Thanks
This question is related to
python
function
parameters
arguments
I guess I'm unclear about what the OP was really asking for... Do you want to pass the whole array/list and operate on it inside the function? Or do you want the same thing done on every value/item in the array/list. If the latter is what you wish I have found a method which works well.
I'm more familiar with programming languages such as Fortran and C, in which you can define elemental functions which operate on each element inside an array. I finally tracked down the python equivalent to this and thought I would repost the solution here. The key is to 'vectorize' the function. Here is an example:
def myfunc(a,b):
if (a>b): return a
else: return b
vecfunc = np.vectorize(myfunc)
result=vecfunc([[1,2,3],[5,6,9]],[7,4,5])
print(result)
Output:
[[7 4 5]
[7 6 9]]
Maybe you want unpack elements of array, I don't know if I got it, but below a example:
def my_func(*args):
for a in args:
print a
my_func(*[1,2,3,4])
my_list = ['a','b','c']
my_func(*my_list)
Source: Stackoverflow.com