Rant (was Re: x*x if x>10

Terry Reedy tjreedy at udel.edu
Sun Jul 27 20:00:27 CEST 2008


DaveM wrote:
> On Sun, 27 Jul 2008 16:57:14 +0200, "Diez B. Roggisch" <deets at nospam.web.de>

> You'll have guessed, I'm sure, that I'm not a professional programmer. This
> was the third rewrite of a program to match candidate groups to examiners on
> a three day course I run, necessitated on this occasion by a change in the
> structure of the course. I originally learnt python as I wrote, and some of
> the early code was ugly and verbose, so once the current rewrite was working
> I took the opportunity to tidy the code up and document it (yes, I know, but
> as I said, I'm an amateur). The list concatenation was an itch I couldn't
> scratch:
> 
>     temp = []
>     for value in sessexam.values():
>         temp.extend(value)
>     c_exam = [name for name in set(temp)] #See what I mean about verbose?
>     c_exam.sort()
>     return c_exam
> 
> Six lines just didn't feel like it ought to be the best way to do something
> so simple. I liked the attempt below better, but was foolish enough to time
> it, so that was the end of that.
> 
>     return sorted(list(set(reduce(lambda x, y: x+y, sessexam.values()))))
> 
> The current version (below) is a compromise, but I still feel there _ought_
> to be a simple one word command to join multiple lists.

There is, as others have posted, but if you are going to dump the lists 
into a set, there is no need to concatenate them together first, and it 
is better not to.  Just dump them directly into set.
> 
>     a = list(set(itertools.chain(*sessexam.values())))

This is a pretty good way of skipping the intermediate long list.  Another:

a = set()
for l in sessexam.values():
   a.update(set(l))

If course, if sessexam.values() does not need to be ordered and returns 
sets instead, the set call in not needed.

>     a.sort() #As I write I'm wondering if I really need it sorted. Hmm...
>     return a

If you want all in one line...
   return sorted(set(itertools.chain(*sessexam.values())))

There is no virtue to calling list then .sort, since that is what sorted 
basically does.

def sorted(iterable):
   tem = list(iterable)
   tem.sort()
   return tem

tjr


tjr




More information about the Python-list mailing list