Swap columns in a nested list (Python 3)

Question:

Using nested lists like this:

``````N = [['D','C','A','B'],
[2,3,4,5],
[6,7,8,9]]
``````

How could I swap two columns? for instance column C and column A.

With a for loop and a little help from this post:

Code:

``````N = [["D","C","A","B"],
[2,3,4,5],
[6,7,8,9]]

# Swap the last two columns

for item in N:
item[2], item[3] = item[3], item[2]

# Or as a function

def swap_columns(your_list, pos1, pos2):
for item in your_list:
item[pos1], item[pos2] = item[pos2], item[pos1]
``````

Output:

``````swap_columns(N, 2, 3)
[['D', 'C', 'B', 'A'], [2, 3, 5, 4], [6, 7, 9, 8]]
``````

Another possibility, using `zip`:

``````In [66]: N = [['D', 'C', 'A', 'B'], [2, 3, 4, 5], [6, 7, 8, 9]]
``````

Transpose using `zip`:

``````In [67]: M = list(zip(*N))
``````

Swap rows 1 and 2:

``````In [68]: M[1], M[2] = M[2], M[1]
``````

Transpose again:

``````In [69]: N2 = list(zip(*M))

In [70]: N2
Out[70]: [('D', 'A', 'C', 'B'), (2, 4, 3, 5), (6, 8, 7, 9)]
``````

The result is a list of tuples. If you need a list of lists:

``````In [71]: [list(t) for t in zip(*M)]
Out[71]: [['D', 'A', 'C', 'B'], [2, 4, 3, 5], [6, 8, 7, 9]]
``````

This doesn’t make the swap in-place. For that, see @DaveTucker’s answer.

``````>>> N = [['D','C','A','B'],
...      [2,3,4,5],
...      [6,7,8,9]]
>>>
>>> lineorder = 0,2,1,3
>>>
>>> [[r[x] for x in lineorder] for r in N]
[['D', 'A', 'C', 'B'], [2, 4, 3, 5], [6, 8, 7, 9]]
``````

If you don’t want the order hardcoded, you can generate it easily like this

``````>>> lineorder = [N[0].index(x) for x in ['D','A','C','B']]
``````

To create a copy of N with two columns swapped, S, in one line, You could do the following:

``````>>> N = [['D','C','A','B'],[2,3,4,5],[6,7,8,9]]
>>> S = [[n[0],n[2],n[1],n[3]] for n in N]
>>> S
[['D', 'A', 'C', 'B'], [2, 4, 3, 5], [6, 8, 7, 9]]
``````

This assumes that each nested list of N are equal in size.

``````l = [1, 2]
emptl = []
for item in l:
empl.append([item[1], item[0]])
``````
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.