How to generically transform a list?

Alex Martelli aleaxit at
Thu Aug 26 23:01:48 CEST 2004

Marco Aschwanden <PPNTWIMBXFFC at> wrote:

> Suppose you have a list of lists:
> theList = [['a',1,11,'aa'], ['b',2,22,'bb'],['c',3,33,'cc']]
> I would like to have a GENERIC way how to turn this list of list into
> another list of list.
> - A user can choose which columns she wants
> - A user can select the order of the columns
> For example:
> The user wants columns: 1,2
> The user wants it to be ordered: 2,1

def GENERIC(list_of_lists, user_wants):
    return [ [row[x] for x in user_wants] for row in list_of_lists ]

example use:

print GENERIC(theList, (2, 1))


[[11, 1], [22, 2], [33, 3]]

> I am sure there must be a rather elegant generic approach, which is 
> lurking somewhere to be realeased.

Funny enough, just this afternoon I was editing a "reordering lists of
lists" recipe for the cookbook's 2nd edition (at the mall, on my iBook,
sitting at a cafe, drinking Schweppes Orange and smoking, while my wife
and co-editor Anna did the grocery shopping -- later she was at the cafe
while I went shopping at the pharmacy, evening things out;-),
and exactly this one came up -- the original author suggested a
hardcoded approach and I widened it up to just this GENERIC function
(with a better name, to be sure, but you insisted;-).  Which is why I
still have it topmost in my mind right now (judging from your post's
timestamp you posted just as I was working on this very recipe, funny

It's one candidate for the 'shortcuts' chapter and there's more stuff
slated for that chapter that we can possibly choose for publication, but
it's interesting info for me that this specific task IS interesting to
somebody -- thanks!-)


More information about the Python-list mailing list