Categories
Post

Transpose in Python

Spread the love

A person on Quora asked how to transpose a list of lists in Python.

As usual I asked myself what is the simplest thing that could possibly work.

This is what I came up with:

def transpose(data):
  visited = []
  for y in range(len(data)):
    for x in range(len(data[0])):
      if (y,x) not in visited:
        data[y][x], data[x][y] = data[x][y], data[y][x]
        visited.append((x,y))
data = [ 
  [0,0,0,0],
  [1,1,1,1],
  [0,0,0,0],
  [1,1,1,1]
]
expected = [ 
  [0, 1, 0, 1], 
  [0, 1, 0, 1], 
  [0, 1, 0, 1], 
  [0, 1, 0, 1]
]

transpose(data)
print(data) 

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.