Catury
Catury

Reputation: 71

How to transpose a 2D list array using loops in python?

Say I have:

a = [[1, 1, 1, 6], [0, 2, -1, 3], [4, 0, 10, 42]]

and I want to transpose it to:

a = [[1,0,4], [1,2,0], [1,-1,10], [6,3,42]]

using loops in python. The current code that I have is:

def transpose(a):
    s = []
    for row in range(len(a)):
        for col in range(len(a)):
            s = s + [a[col][row]]
return s

But this gives me the output of:

[1, 0, 4, 1, 2, 0, 1, -1, 10]

Instead of this:

[[1,0,4], [1,2,0], [1,-1,10], [6,3,42]]

Can anyone help me? I'm still new at this stuff and don't understand why it doesn't work. Thanks so much!

Upvotes: 2

Views: 3310

Answers (3)

Moinuddin Quadri
Moinuddin Quadri

Reputation: 48067

If you are looking for a solution without any fancy function. You may achieve it using list comprehension as:

>>> a = [[1, 1, 1, 6], [0, 2, -1, 3], [4, 0, 10, 42]]
>>> sublist_size = len(a[0])
>>> [[item[i] for item in a] for i in range(sublist_size)]
[[1, 0, 4], [1, 2, 0], [1, -1, 10], [6, 3, 42]]

However, simplest way is by using zip():

>>> list(zip(*a))  # for Python 3, OR, just zip(*a) in Python 2 
[(1, 0, 4), (1, 2, 0), (1, -1, 10), (6, 3, 42)]

Upvotes: 0

Maurice
Maurice

Reputation: 13108

Here is a solution that is based on your code:

def transpose(a):
    s = []
    # We need to assume that each inner list has the same size for this to work
    size = len(a[0])
    for col in range(size):
        inner = []
        for row in range(len(a)):
            inner.append(a[row][col])
        s.append(inner)
    return s

If you define an inner list for the inner loop, your output is this:

[[1, 0, 4], [1, 2, 0], [1, -1, 10], [6, 3, 42]]

Upvotes: 1

shaktimaan
shaktimaan

Reputation: 12092

Use zip()

>>> a = [[1, 1, 1, 6], [0, 2, -1, 3], [4, 0, 10, 42]]
>>> [list(x) for x in zip(*a)]
[[1, 0, 4], [1, 2, 0], [1, -1, 10], [6, 3, 42]]

zip(*a) unpacks the three sub-lists in a and combines them element by element. Meaning, the first elements of the each of the three sub-lists are combined together, the second elements are combined together and so on. But zip() returns tuples instead of lists like you want in your output. Like this:

>>> zip(*a)
[(1, 0, 4), (1, 2, 0), (1, -1, 10), (6, 3, 42)]

[list(x) for x in zip(*a)] converts each of the tuples to lists giving the output the way you need it.

Upvotes: 1

Related Questions