views:

144

answers:

3

How to run an operation on a collection in Python and collect the results?

So if I have a list of 100 numbers, and I want to run a function like this for each of them:

Operation ( originalElement, anotherVar ) # returns new number.

and collect the result like so:

result = another list...

How do I do it? Maybe using lambdas?

+9  A: 

List comprehensions. In Python they look something like:

a = [f(x) for x in bar]

Where f(x) is some function and bar is a sequence.

You can define f(x) as a partially applied function with a construct like:

def foo(x):
    return lambda f: f*x

Which will return a function that multiplies the parameter by x. A trivial example of this type of construct used in a list comprehension looks like:

>>> def foo (x):
...     return lambda f: f*x
... 
>>> a=[1,2,3]
>>> fn_foo = foo(5)
>>> [fn_foo (y) for y in a]
[5, 10, 15]

Although I don't imagine using this sort of construct in any but fairly esoteric cases. Python is not a true functional language, so it has less scope to do clever tricks with higher order functions than (say) Haskell. You may find applications for this type of construct, but it's not really that pythonic. You could achieve a simple transformation with something like:

>>> y=5
>>> a=[1,2,3]
>>> [x*y for x in a]
[5, 10, 15]
ConcernedOfTunbridgeWells
foo(x, anotherVar)?
Mykola Golubyev
Thanks, this is pretty good syntax.
Joan Venge
Mykola: Depending on what you want I'd say y = 4; a = [f(x, y) for x in bar] or a = [f(x, y) for x, y in zip(bar, baz)]. Also see izip.
Henrik Gustafsson
For simple operations you don't even need to define a separate function for the operation, but can do it "inline", like in squares = [x*x for x in a]
sth
+1  A: 

Another (somewhat depreciated) method of doing this is:

def kevin(v): return v*v

vals = range(0,100)

map(kevin,vals)

kkubasik
IIRC this is kept as a legacy feature but implemented as a wrapper around list comprehensions.
ConcernedOfTunbridgeWells