[Solved] Swap two numbers in list of tuples (python)


For anyone curious, I quickly wrote a function for it. First off, the complete matching is written as a 2D list.

The following function is needed before writing the main one:

def index_2d(myList, v): #Returns tuple containing the position of v in the 2D list
  for i, x in enumerate(myList):
     if v in x:
        return (i, x.index(v))

eg. If the complete matching is M=[[1,2],[3,4],[5,6]], index_2d(M, 4) would return (1,1).

Next, the simple transposition function:

def s(M,n):
   a=index_2d(M,n)
   b=index_2d(M,n+1)
   M[a[0]][a[1]], M[b[0]][b[1]] = M[b[0]][b[1]], M[a[0]][a[1]]
   return M

I wasn’t concerned with efficiency, so perhaps there is more efficient code than this.

solved Swap two numbers in list of tuples (python)