Moving to functional programming

craig75 craig.pastro at gmail.com
Fri Jul 11 13:08:26 EDT 2008


On Jul 11, 3:36 am, bearophileH... at lycos.com wrote:
> 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


Functional programmers love pattern matching (which I think makes the
code much easier to understand):

[x for (x,y) in tuple_list]

or

map(lambda (x,y):x, tuple_list)




More information about the Python-list mailing list