Python | Swapping Elements in a List

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]

Gagan

Hi, there I'm founder of ComputerScienceHub(Started this to bring useful Computer Science information just at one place). Personally I've been doing JavaScript, Python development since 2015(Been long) - Worked upon couple of Web Development Projects, Did some Data Science stuff using Python. Nowadays primarily I work as Freelance JavaScript Developer(Web Developer) and on side-by-side managing team of Computer Science specialists at ComputerScienceHub.io

Leave a Reply

Your email address will not be published. Required fields are marked *

Recent Posts