Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 375
user1020069 Avatar asked Aug 12 '12 23:08

user1020069


People also ask

How do you pass an array as a function argument in Python?

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.

What do you pass to a function to pass an array as an argument to a function?

To pass an entire array to a function, only the name of the array is passed as an argument. result = calculateSum(num); However, notice the use of [] in the function definition. This informs the compiler that you are passing a one-dimensional array to the function.

How an array can be passed to a function as an argument?

If you want to pass a single-dimension array as an argument in a function, you would have to declare a formal parameter in one of following three ways and all three declaration methods produce similar results because each tells the compiler that an integer pointer is going to be received.


2 Answers

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.

like image 123
Russell Borogove Avatar answered Sep 28 '22 06:09

Russell Borogove


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) 
like image 37
fabiocerqueira Avatar answered Sep 28 '22 05:09

fabiocerqueira