user33061
user33061

Reputation: 1875

python, functions running from a list and adding to a list through functions

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

Answers (3)

Vinko Vrsalovic
Vinko Vrsalovic

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

gone
gone

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

tzot
tzot

Reputation: 95911

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.

Upvotes: 1

Related Questions