Making things more functional in Python

Bill Mill bill.mill at
Fri Mar 4 18:09:50 CET 2005

On Fri, 4 Mar 2005 08:36:49 -0800 (PST), gf gf
<unknownsoldier93 at> wrote:
> Is there a better, more FP style, more Pythonic way to
> write this:
> def compute_vectors(samples, dset):
>         vectors = {}
>         for d in dset:
>                 vectors[d] = [sample.get_val(d) for sample in
> samples]
>         return vectors
> Namely, I'd like to get rid of the initilization
> (vectors = {}) and also the loop  Yet, I'd hate to put
> an assignment into Python's FP list comprehensions.

Well, I guess it's a little more FP, but whether it's (IMHO) way
*less* pythonic:

return dict([(d, [sample.get_val(d) for sample in samples]) 
                      for d in dset])

it should work, but is untested and really ugly. I don't see what's
wrong with your code that you need to compress it. It's blindingly
obvious what your code does, which is a good thing. My list comp, on
the other hand, is seven kinds of confusing for a reader.

Bill Mill
bill.mill at

More information about the Python-list mailing list