user1020069
user1020069

Reputation: 1570

Declaring a python function with an array parameters and passing an array argument to the function call?

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

Upvotes: 35

Views: 301882

Answers (3)

fabiocerqueira
fabiocerqueira

Reputation: 812

Maybe you want to unpack elements of an array, I don't know if I got it, but below an 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)

Upvotes: 26

user4533269
user4533269

Reputation: 31

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]]

Upvotes: 3

Russell Borogove
Russell Borogove

Reputation: 19037

What you have is on the right track.

def dosomething( thelist ):
    for element in thelist:
        print element

dosomething( ['1','2','3'] )
alist = ['red','green','blue']
dosomething( alist )  

Produces the output:

1
2
3
red
green
blue

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.

Upvotes: 45

Related Questions