35

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

4
  • 2
    It should work. Could you show some real code? Commented Aug 12, 2012 at 23:24
  • 1
    Could you provide some more context, maybe the actual code that fails? (If possible, make it a good example). And what do you mean by declaring? Commented Aug 12, 2012 at 23:25
  • oh yes it is absolutely my bad...i was doing this: for x in range(len(list)): print x; instead of print list[x] ...thanks all! Commented Aug 12, 2012 at 23:35
  • 2
    This looks correct; are you getting a specific error message? Perhaps you have not declared / put something inside listargument? Commented Aug 12, 2012 at 23:36

3 Answers 3

45

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I think you mean enumerate(list)
26

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)

Comments

3

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.