Welcome, guest | Sign In | My Account | Store | Cart

By using the zip builtin function you can easily convert a list of lists into a transposed list of tuples. This can be used for easily selecting columns.

Python, 19 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
>>> a=[[0,1],[0,1],[0,1]]
>>> print=zip(*a) #passes the lists in a as separate arguments 
[(0, 0, 0), (1, 1, 1)]
>>> print zip(*a)[0] #prints the first column
(0, 0, 0)

>>> a=[[0,1],[0,1,2],[0,1]] #lets see what happens when we use a "ragged" list
>>> print zip(*a) # the transpose is truncated to the shortest row
[(0, 0, 0), (1, 1, 1)]

>>> a=[[0,1],[0,1],[0,1],0] #What if there are not only lists in the list
>>> print zip(*a) #This does not work, so watch out for it.
Traceback (most recent call last):
  File "<interactive input>", line 1, in ?
TypeError: zip argument #4 must support iteration

>>> a=[(0,1),(0,1),(0,1)] #Does it work on a list of tuples?
>>> zip(*a) #Yes because a tuple is iterable.
[(0, 0, 0), (1, 1, 1)]

This approach can be used if you get data from a database and you easily want to extract a column. Note that the result is always a tuple and not a list. It shouldn't be used as a matrix-transpose. You should use the Numeric, or Numarray module for that. It can be confusing when you first see it.

2 comments

C Smith 19 years, 1 month ago  # | flag

you can pad the lists to prevent truncation. If you don't want to loose the elements in the longer lists,

you can pad the short ones with the following:

def pad(l, padding=None):
    '''Add padding to short lists to make all
    lists in l have the same length.'''

    lengths = [len(li) for li in l]
    big = max(lengths)
    if lengths.count(big)
If you don't want to loose the elements in the longer lists,

you can pad the short ones with the following:


<pre>
def pad(l, padding=None):
    '''Add padding to short lists to make all
    lists in l have the same length.'''

    lengths = [len(li) for li in l]
    big = max(lengths)
    if lengths.count(big)

</pre>

Zoran Isailovski 18 years, 11 months ago  # | flag

... or you can use map to pad automatically ... ... like described in this recipe:

http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/410687

Created by Fee Thee on Thu, 15 May 2003 (PSF)
Python recipes (4591)
Fee Thee's recipes (1)

Required Modules

  • (none specified)

Other Information and Tasks