Python Lists are Mutable Objects, meaning these once created can be changed. For example – In a Python Program if there is a list [10, 29, 28] then it can be changed to [10, 28] or to some other form. Anyway, in this article I’ll discuss How to swap two elements in a Python List?
Python Code for Swapping Elements in a List
- Define a Python List like a_list = [10, 28, 18, 84, 162, 83]
- Define a Python Function like def swapping(a_list, first_pos, second_pos) which takes in a Python List, two index positions and return a list with swapped elements at specified indexes
# Python Code for Swapping Elements in a List a_list = [10, 28, 18, 84, 162, 83] # Defining Some List def swapping(a_list, first_pos, second_pos): a_list[first_pos], a_list[second_pos] = a_list[second_pos], a_list[first_pos] return a_list # Let's swap element at index 1 with that at index 4 in List print("List after swapping elements in =>", swapping(a_list, 1, 4))
Output of Above Code
List after swapping elements in => [10, 162, 18, 84, 28, 83]