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

Question:

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!

Asked By: TSX

||

Answers:

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]
Answered By: Madison Courto

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 🙂

Answered By: Vivek Maddeshiya

you can simply use list functions to swap the lists.

Answered By: Himanshu Gupta
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.