views:

527

answers:

3

How do I run a function on a loop so all the results go straight into a list and is there a way to run a function which acts on all the values in a list?

A: 
>>> def square(x):
...  return x*x
...
>>> a = [1,2,3,4,5,6,7,8,9]

>>> map(square,a)
[1, 4, 9, 16, 25, 36, 49, 64, 81]
Vinko Vrsalovic
+1  A: 

Your question needs clarification.

run a function on a loop

new_list= [yourfunction(item) for item in a_sequence]

run a function acting on all values in a list

Your function should have some form of iteration in its code to process all items of a sequence, something like:

def yourfunction(sequence):
    for item in sequence:
        …

Then you just call it with a sequence (i.e. a list, a string, an iterator etc)

yourfunction(range(10))
yourfunction("a string")

YMMV.

ΤΖΩΤΖΙΟΥ
+6  A: 

Theres a couple ways to run a function on a loop like that - You can either use a list comprehension

test = list('asdf')
[function(x) for x in test]

and use that result

Or you could use the map function

test = list('asdf')
map(function, test)

The first answer is more "pythonic", while the second is more functional.

EDIT: The second way is also a lot faster, as it's not running arbitrary code to call a function, but directly calling a function using map, which is implemented in C.

kanja
important note - the second way is much, much faster
Claudiu