Valerie Valerie - 4 months ago 20
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']

Answer
[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!

In your case, you'd do:

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)

Output:

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