Moving to functional programming

bearophileHUGS at lycos.com bearophileHUGS at lycos.com
Fri Jul 11 06:36:45 EDT 2008


James Fassett:
> # the first Pythonic attempt using comprehensions
> result_list = [x[0] for x in tuple_list]
>
> # the final functional way
> [result_list, _] = zip(*tuple_list)
>
> I really like how Python allows me to do what I feel is the most
> natural solution (for a seasoned procedural programmer) while allowing
> a satisfying path towards a more functional approach.

The list comprehension is quite more readable to me, so I suggest you
to use it. It's probably the default way to do it in Python.

If you want functional code this is another way (I have not tested the
relative performance but it may be quick):

>>> tuple_list = (
...     ('John', 'Doe'),
...     ('Mark', 'Mason'),
...     ('Jeff', 'Stevens'),
...     ('Bat', 'Man')
...   )
>>> from operator import itemgetter
>>> map(itemgetter(0), tuple_list)
['John', 'Mark', 'Jeff', 'Bat']

Bye,
bearophile



More information about the Python-list mailing list