Moving Python List Columns

I am trying to move the second value in the list to the third value in the list for each nested list. I tried below, but it does not work properly.

the code

List = [['a','b','c','d'],['a','b','c','d'],['a','b','c','d']]
print(List)
col_out = [List.pop(1) for col in List]
col_in = [List.insert(2,List) for col in col_out]
print(List)

Result

[['a', 'b', 'c', 'd'], ['a', 'b', 'c', 'd'], ['a', 'b', 'c', 'd']]
[['a', 'b', 'c', 'd'], [...], [...]]

Desired Result

[['a', 'c', 'b', 'd'], ['a', 'c', 'b', 'd'], ['a', 'c', 'b', 'd']]

UPDATE

Based on pynoobs comment, I came up with the following. But I'm still not there. Why print 'c'?

the code

List = [['a','b','c','d'],['a','b','c','d'],['a','b','c','d']]
col_out = [col.pop(1) for col in List for i in col]
print(col_out)

Result

['b', 'c', 'b', 'c', 'b', 'c']
+4
source share
2 answers
[List.insert(2,List) for col in col_out]
               ^^^^ -- See below.

You insert the whole list as an element in one list. Think of recursion!


Also, please refrain from using stateful expressions in the list comprehension. Understanding the list should NOT change any variables. These are bad manners!

:

lists = [['a','b','c','d'],['a','b','c','d'],['a','b','c','d']]
for lst in lists:
    lst[1], lst[2] = lst[2], lst[1]
print(lists)

:

[['a', 'c', 'b', 'd'], ['a', 'c', 'b', 'd'], ['a', 'c', 'b', 'd']]
+2

:

myList = [['a','b','c','d'],['a','b','c','d'],['a','b','c','d']]
myOrder = [0,2,1,3] 
myList = [[sublist[i] for i in myOrder] for sublist in myList]
0

All Articles