Home > database >  Swap first 2 rows of a 2d Python list without Numpy?
Swap first 2 rows of a 2d Python list without Numpy?

Time:08-31

How can I swap the first 2 rows of a 2D Python list without using Numpy? For example, if my list is:

lst = [[0,3,2],
       [4,3,2],
       [3,5,2]]

I want to swap [0,3,2] with [4,3,2].

Thanks!

CodePudding user response:

Something like this? Or do you need it to be a function to swap when needed?

lst = [[0,3,2],
       [4,3,2],
       [3,5,2]]

lst[0], lst[1] = lst[1], lst[0]
print(lst)
# [[4, 3, 2], 
# [0, 3, 2], 
# [3, 5, 2]

CodePudding user response:

store the second value (lst[1]) in a temporary variable swap the variable

lst = [[0,3,2],
       [4,3,2],
       [3,5,2]]
a= lst[1]
lst[1] = lst[0]
lst[0] = a

hope it helps :)

  • Related