Skip to content Skip to sidebar Skip to footer

Transpose A List

Suppose i have a nested list m = [[2, 3], [4, 7]] and I want to transpose it such that I get [[2, 4], [3, 7]] OR if m can be [[1,2,3],[4,5,6],[7,8,9]] then after passing through

Solution 1:

Use zip function

print zip(*[[2, 3], [4, 7]])
# [(2, 4), (3, 7)]

So, your transpose function becomes like this

def transpose(m):
    return zip(*m)

assert transpose([[2, 3], [4, 7]]) == [(2, 4), (3, 7)]
assert transpose([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) == [
    (1, 4, 7), (2, 5, 8), (3, 6, 9)]

Remember, it just returns a list of tuples. They can be used almost interchangeably, except for the facts that the syntaxes for creating them is different and tuples are immutable.

If you really want to get only list of lists, you have throw in a comprehension or a map function, like this

def transpose(m):
    return [list(item) in zip(*m)]
    # return map(list, zip(*m))

assert transpose([[2, 3], [4, 7]]) == [[2, 4], [3, 7]]assert transpose([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) == [
    [1, 4, 7], [2, 5, 8], [3, 6, 9]]
assert transpose([[1, 2, 3], [4, 5, 6]]) == [[1, 4], [2, 5], [3, 6]]

Post a Comment for "Transpose A List"