pmv pmv - 10 months ago 28
Python Question

python loop function to loop another function over a list

I have a function called

. I want to loop this function over a list.
I want to create a
function and pass the
and the
function to loop over as input

def add_ten(x):
y = x+10
print 'value of x is ' + str(x)
print 'value of y is ' + str(y)

def looper(list,func):
for i in list:
return func(i)

I call the looper function


I get this error.

TypeError Traceback (most recent call last)
<ipython-input-27-6510e446c709> in <module>()
----> 1 looper([1,2],add_ten())

TypeError: add_ten() takes exactly 1 argument (0 given)

How do I create the looper function properly so that it takes the right arguments?


Trying to understand the question, I arrive at the following working code:

#! /usr/bin/env python
from __future__ import print_function

def add_ten(x):
    print('value of x is %s\nvalue of y is %s' % (str(x), str(x + 10)))

def looper(list, func):
    for i in list:

if __name__ == '__main__':
    looper([1, 2], add_ten)

Output is on my machine:

value of x is 1
value of y is 11
value of x is 2
value of y is 12

Hope this helps in learning Python ;-)

Note in the implementation of looperyou for sure do not want to return early in the first iteration, as then only the first list element is processed with a result. Here above I just call it and the side effect of the print or whatever is defined in add_ten "happens" ...