# What is the slickest way to transpose a square list of lists (tuple of tuples)?

Dave Hansen iddw at hotmail.com
Mon Jan 9 17:05:11 CET 2006

```On Sun, 08 Jan 2006 14:27:55 -0500 in comp.lang.python, Gerard Brunick
<gbrunick at andrew.cmu.edu> wrote:

>My way is ugly.  These has to be a better way.

This may not be the "slickest" way, but I needed some practice with
list comprehensions (I've never really gotten used to them...)

This works with lists.  Making it work with tuples should be a simple
change.  Also, it works for the general case of rectangular matrices
rather than being limited to squares.

>>> def transpose(m):
"""
Transpose the rectangular two-dimentional matrix m.
"""
return [[m[y][x] for y in range(len(m))]for x in
range(len(m[0]))]

>>> def pm(m):
"""
Print the matrix m.  Just to see the results.
"""
for row in m:
print row

>>> td = [range(10) for x in range(10)]
>>> pm(td)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> pm(transpose(td))
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
[2, 2, 2, 2, 2, 2, 2, 2, 2, 2]
[3, 3, 3, 3, 3, 3, 3, 3, 3, 3]
[4, 4, 4, 4, 4, 4, 4, 4, 4, 4]
[5, 5, 5, 5, 5, 5, 5, 5, 5, 5]
[6, 6, 6, 6, 6, 6, 6, 6, 6, 6]
[7, 7, 7, 7, 7, 7, 7, 7, 7, 7]
[8, 8, 8, 8, 8, 8, 8, 8, 8, 8]
[9, 9, 9, 9, 9, 9, 9, 9, 9, 9]
>>> td2 = [range(10) for x in range(5)]
>>> pm(td2)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> pm(transpose(td2))
[0, 0, 0, 0, 0]
[1, 1, 1, 1, 1]
[2, 2, 2, 2, 2]
[3, 3, 3, 3, 3]
[4, 4, 4, 4, 4]
[5, 5, 5, 5, 5]
[6, 6, 6, 6, 6]
[7, 7, 7, 7, 7]
[8, 8, 8, 8, 8]
[9, 9, 9, 9, 9]
>>>

Regards,
-=Dave

--
Change is inevitable, progress is not.

```

More information about the Python-list mailing list