Howto: extract a 'column' from a list of lists into a new list?

John Hunter jdhunter at ace.bsd.uchicago.edu
Tue Jul 1 21:07:58 EDT 2003


>>>>> "Bengt" == Bengt Richter <bokr at oz.net> writes:

    >>>> zip(*fields)

That is amazingly helpful.  I've often needed to transpose a 2d list,
(mainly to get a "column" from an SQL query of a list of rows) and
this is just the trick.

I recently wrote a function to "deal" out a list of MySQLdb results,
where each field was a numeric type, and wanted to fill numeric arrays
with each column of results

With your trick, eg, for a list of results from three numeric fields,
I just have to do:

  a1, a2, a3 =  map(array, zip(*results))

John Hunter





More information about the Python-list mailing list