Valerie - 1 year ago 144
Python Question

# Python List Column Move

I'm trying to move the second value in a list to the third value in a list for each nested list. I tried the below, but it's not working as expected.

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 upon pynoobs comment, i came up with the following. But i'm still not there. Why is 'c' printing?

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']
``````

``````[List.insert(2,List) for col in col_out]
^^^^ -- See below.
``````

You are inserting an entire list as an element within the same list. Think recursion!

Also, please refrain from using state-changing expressions in list comprehension. A list comprehension should NOT modify any variables. It is bad manners!

``````lists = [['a','b','c','d'],['a','b','c','d'],['a','b','c','d']]
``````[['a', 'c', 'b', 'd'], ['a', 'c', 'b', 'd'], ['a', 'c', 'b', 'd']]