Declaring a python function with an array parameters and passing an array argument to the function call?
What you have is on the right track.
def dosomething( thelist ): for element in thelist: print elementdosomething( ['1','2','3'] )alist = ['red','green','blue']dosomething( alist )
Produces the output:
123redgreenblue
A couple of things to note given your comment above: unlike in C-family languages, you often don't need to bother with tracking the index while iterating over a list, unless the index itself is important. If you really do need the index, though, you can use enumerate(list)
to get index,element
pairs, rather than doing the x in range(len(thelist))
dance.
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 amy_func(*[1,2,3,4])my_list = ['a','b','c']my_func(*my_list)
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 bvecfunc = np.vectorize(myfunc)result=vecfunc([[1,2,3],[5,6,9]],[7,4,5])print(result)
Output:
[[7 4 5] [7 6 9]]