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
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.
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.
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.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With