Nick Rogers
Nick Rogers

Reputation: 13

How to flip the rows of a list horizontally using slicing operator in python?

def matrixflip(myl,c):
   if(c=='v'):
       myl=myl[::-1]
       return myl
   elif(c=='h'):
       myl=myl[::][::-1]
       return myl
   else:
       return myl

myl=[[1, 2], [3, 4]]
print(matrixflip(myl,'h'))

Expected output: [[2,1],[4,3]]

In the above code I'm calling the matrixflip() function to flip the rows of list/ flip the 2d matrix horizontally by passing the second argument as 'h'. However, i still get the vertically flipped version.

Upvotes: 1

Views: 1312

Answers (1)

Mureinik
Mureinik

Reputation: 311723

You need to reverse each sublist. The easiest way to do this is probably with a list comprehension expression:

result = [x[::-1] for x in myl]

Upvotes: 1

Related Questions