Reputation: 1875
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?
Upvotes: -1
Views: 3286
Reputation: 340181
This example shows how to do it (run it in an interpreter)
>>> 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]
Upvotes: 0
Reputation: 4502
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.
Upvotes: 8
Reputation: 95911
Your question needs clarification.
new_list= [yourfunction(item) for item in a_sequence]
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.
Upvotes: 1