Search code examples
pythonlist2dswap

Swapping Columns of 2D List


With a 2d list such as:

[['G', 'Y', 'V', 'X'], ['C', 'F', 'Z', 'Y'], ['B', 'X', 'B', 'J'], ['P', 'T', 'U', 'W']]

Is there a BIF/shorthand that would allow swapping, like the example below where each 0th index of each inner lists have been swapped with the 2nd index of the inner lists:

[['V', 'Y', 'G', 'X'], ['Z', 'F', 'C', 'Y'], ['B', 'X', 'B', 'J'], ['U', 'T', 'P', 'W']]

I have produced an iterative solution which works fine. But it would be nice to know if a BIF does exist. Thanks in advance.


Solution

  • If you want to do the swapping in place (which I assume), I'd to it like this:

    def swap_in(lst, fro, to):
        lst[fro], lst[to] = lst[to], lst[fro]
    
    lst = [['G', 'Y', 'V', 'X'], ['C', 'F', 'Z', 'Y'], ['B', 'X', 'B', 'J'], ['P', 'T', 'U', 'W']]
    
    for sublist in lst:
        swap_in(sublist, 0, 2)
    
    print(lst) # [['V', 'Y', 'G', 'X'], ['Z', 'F', 'C', 'Y'], ['B', 'X', 'B', 'J'], ['U', 'T', 'P', 'W']]
    

    I don't know of any neat oneliner that is readable and does the trick.