Better writing in python

Neil Cerutti horpner at
Wed Oct 24 15:13:54 CEST 2007

On 2007-10-24, Alexandre Badez <alexandre.badez at> wrote:
> I'm just wondering, if I could write a in a "better" way this
> code
> lMandatory = []
> lOptional = []
> for arg in cls.dArguments:
>   if arg is True:
>     lMandatory.append(arg)
>   else:
>     lOptional.append(arg)
> return (lMandatory, lOptional)
> I think there is a better way, but I can't see how...

I don't think there's much improvement to be made. What are your
particular concerns? Is it too slow? Too verbose? Does it not
work correctly?

It appears to be an application of itertools.groupby, but that'll
almost certainly be less efficient. To use groupby, you have to
sort by your predicate, and build lists to save results. Your for
loop avoids the sorting.

Here's some instrumentality for ya:

from itertools import groupby
from operator import truth
from collections import defaultdict

result = defaultdict(list)
for k, g in groupby(sorted(cls.dArguments, key=truth), truth):

I like your initial attempt better.

P.S. I didn't realize until working out this example that extend
could consume an iterator.

Neil Cerutti
The word "genius" isn't applicable in football. A genius is a guy like Norman
Einstein. --Joe Theisman

More information about the Python-list mailing list