[Tutor] List comprehensions

jfouhy at paradise.net.nz jfouhy at paradise.net.nz
Thu Jan 13 00:47:24 CET 2005


Quoting Liam Clarke <cyresse at gmail.com>:

> As a comprehension, if you get what I mean... Can I build a for loop
> with a function in for x in x part?
> 
> Ack. Having difficulty summing it up properly.

I'm not sure exactly what you mean, so my answer is "probably".

>>> from math import sin
>>> arr = range(10)
>>> arr
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> [sin(float(x)/10) for x in arr]
[0.0, 0.099833416646828155, 0.19866933079506122, 0.29552020666133955,
0.38941834230865052, 0.47942553860420301, 0.56464247339503537,
0.64421768723769102, 0.71735609089952279, 0.78332690962748341]
>>> def biggerThanHalf(x):
...     return x > 0.5
...
>>> [biggerThanHalf(sin(float(x)/10)) for x in arr]
[False, False, False, False, False, False, True, True, True, True]
>>> [biggerThanHalf(sin(float(x)/10)) for x in map(lambda y: 2*y + 3, arr)]
[False, False, True, True, True, True, True, True, True, True]

Hopefully one of these examples answers your question :-)

-- 
John.


More information about the Tutor mailing list